Reputation: 13555
var patt = path.match(/P[0-9][0-9][0-9]/);
patt = patt.substr(1); //Remove P
while(patt.charAt(0) === '0') { //Remove 0
patt = patt.substr(1);
}
alert(patt);
patt
is fixed to this format:
eg. P001
to P999
What I would like to do is very basic, just remove P
and the leading 0
(if any). However, the code above is not working. Thanks for helping
Upvotes: 0
Views: 602
Reputation: 6000
This seems the perfect use case for the global parseInt
function.
parseInt(patt.substr(1), 10);
It takes as input the string you want to parse, and the base. The base is optional, but most people suggest to always explicitly set the base to avoid surprises which may happen in some edge case.
It stops to parse the string as soon as it encounters a not numerical value (blank spaces excluded). For this reason in the snippet above we're a passing the input string stripped of the first character, that as you've mentioned, is the letter "P".
Also, ES2015 introduced a parseInt
function, as static method on the Number
constructor.
Upvotes: 1
Reputation: 1588
Just a single line and you get what you want
var path = "P001"; //your code from P001 - P999
solution to remove P and the leading "0" .
parseInt(path.substr(1), 10);
Thanks and Regards
Upvotes: 0
Reputation: 19173
If the input to this function is guaranteed to be valid (i.e. of the form P001...P999), then you can simply use the following to extract the integer:
parseInt(path.substr(1), 10)
Upvotes: 1
Reputation: 7452
Please use it like this:
var str = patt.join('');
str = str.replace(/P0*/, '');
Upvotes: 11