Remove specific characters from a string in Javascript

JavascriptString

Javascript Problem Overview


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();

Javascript Solutions


Solution 1 - Javascript

Simply replace it with nothing:

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

Solution 2 - Javascript

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.

Solution 3 - Javascript

Another way to do it:

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

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

Solution 4 - Javascript

Regexp solution:

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

plain solution:

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

Solution 5 - Javascript

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);

Solution 6 - Javascript

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);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlphaPapaView Question on Stackoverflow
Solution 1 - JavascriptMathias BynensView Answer on Stackoverflow
Solution 2 - JavascriptStormsEngineeringView Answer on Stackoverflow
Solution 3 - Javascriptpaulslater19View Answer on Stackoverflow
Solution 4 - JavascriptBergiView Answer on Stackoverflow
Solution 5 - JavascriptPenny LiuView Answer on Stackoverflow
Solution 6 - JavascriptEissa SaberView Answer on Stackoverflow