AlphaPapa
AlphaPapa

Reputation: 713

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

Upvotes: 61

Views: 176967

Answers (6)

Penny Liu
Penny Liu

Reputation: 17388

If you wish to remove all occurrences of F0 from a given string, you can use the replaceAll() method.

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

Upvotes: 15

paulslater19
paulslater19

Reputation: 5917

Another way to do it:

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

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

Upvotes: 9

Eissa Saber
Eissa Saber

Reputation: 189

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

Upvotes: 3

StormsEngineering
StormsEngineering

Reputation: 686

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.

Upvotes: 30

Mathias Bynens
Mathias Bynens

Reputation: 149484

Simply replace it with nothing:

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

Upvotes: 91

Bergi
Bergi

Reputation: 664185

Regexp solution:

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

plain solution:

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

Upvotes: 8

Related Questions