[英]Remove all leading zeros from numeric string
I have the below case: 我有以下情况:
I want to remove all leading zeros from the string using JavaScript 我想使用JavaScript从字符串中删除所有前导零
What is the best way to accomplish this? 做到这一点的最佳方法是什么?
您可以使用正则表达式来匹配字符串开头的零:
str = str.replace(/^0+/, '');
parseInt()
will do the job. parseInt()
将完成这项工作。
var num = '00898989899';
parseInt( num, 10 ); // 898989899
Don't forget about the radix argument, especially since you're dealing with leading zeros here. 不要忘记基数参数,尤其是在这里要处理前导零时。
If you can be sure that there won't be any zero digit after those leading zeros, you can even go more sneaky and use a combination of String.prototype.lastIndexOf()
and String.prototype.slice()
: 如果您可以确定在前导零之后不会有任何零数字,那么您甚至可以偷偷摸摸地使用String.prototype.lastIndexOf()
和String.prototype.slice()
:
num.slice( num.lastIndexOf( '0' ) + 1 );
parseInt(number, 10)
您可以将其转换为字符串(如果需要)
parseInt(number, 10).toString()
为什么不只使用parseInt-
parseInt(00898989899);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.