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();
Solution 1:
Simply replace it with nothing:
var string = 'F0123456'; // just an example
string.replace(/^F0+/i, ''); '123456'
Solution 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.
Solution 3:
Another way to do it:
rnum = rnum.split("F0").pop()
It splits the string into two: ["", "123456"]
, then selects the last element.
Solution 4:
Regexp solution:
ref = ref.replace(/^F0/, "");
plain solution:
if (ref.substr(0, 2) == "F0")
ref = ref.substr(2);