简体   繁体   English

JavaScript中的字符串处理(删除前导零和特定字符)

[英]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. patt固定为以下格式: P001 to P999 P001P999

What I would like to do is very basic, just remove P and the leading 0 (if any). 我想做的是非常基本的,只需删除P和前导0 (如果有)。 However, the code above is not working. 但是,上面的代码不起作用。 Thanks for helping 感谢您的帮助

Please use it like this: 请像这样使用它:

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

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

parseInt(path.substr(1), 10)

This seems the perfect use case for the global parseInt function. 这似乎是全局parseInt函数的完美用例。

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". 因此,在上面的代码段中,我们传递了去除了第一个字符的输入字符串,正如您所提到的,它是字母“ P”。

Also, ES2015 introduced a parseInt function, as static method on the Number constructor. 此外,ES2015引入了parseInt函数,作为Number构造函数上的静态方法。

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" . 解决方案,删除P和前导“ 0”。

parseInt(path.substr(1), 10);

Thanks and Regards 谢谢并恭祝安康

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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