[javascript] Remove specific characters from a string in Javascript

I am creating a form to lookup the details of a support request in our call logging system.

Call references are assigned a number like F0123456 which is what the user would enter, but the record in the database would be 123456. I have the following code for collecting the data from the form before submitting it with jQuery ajax.

How would I strip out the leading F0 from the string if it exists?

$('#submit').click(function () {        
            
var rnum = $('input[name=rnum]');
var uname = $('input[name=uname]');

var url = 'rnum=' + rnum.val() + '&uname=' + uname.val();

This question is related to javascript string

The answer is


Regexp solution:

ref = ref.replace(/^F0/, "");

plain solution:

if (ref.substr(0, 2) == "F0")
     ref = ref.substr(2);

Honestly I think this probably the most concise and least confusing, but maybe that is just me:

str = "F0123456";
str.replace("f0", "");

Dont even go the regular expression route and simply do a straight replace.


Another way to do it:

rnum = rnum.split("F0").pop()

It splits the string into two: ["", "123456"], then selects the last element.


If you want to remove F0 from the whole string then the replaceAll() method works for you.

_x000D_
_x000D_
const str = 'F0123F0456F0'.replaceAll('F0', '');
console.log(str);
_x000D_
_x000D_
_x000D_


if it is not the first two chars and you wanna remove F0 from the whole string then you gotta use this regex

_x000D_
_x000D_
   let string = 'F0123F0456F0';_x000D_
   let result = string.replace(/F0/ig, '');_x000D_
   console.log(result);
_x000D_
_x000D_
_x000D_