简体   繁体   中英

String manipulation in javascript (remove leading zero & specific character)

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

Please use it like this:

var str = patt.join('');
str = str.replace(/P0*/, '');

如果保证此函数的输入有效(即格式为P001 ... P999),则可以使用以下命令提取整数:

parseInt(path.substr(1), 10)

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM