Remove Specific Characters from a String in 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();
1

6 Answers

Simply replace it with nothing:

var string = 'F0123456'; // just an example
string.replace(/^F0+/i, ''); '123456'
3

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.

0

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

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

Regexp solution:

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

plain solution:

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

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sophia Al-Mansoor
Author

Sophia Al-Mansoor

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.