移除数字前导零的 JavaScript 正则表达式?


要移除前导零,请在 replace() 方法中使用 Regex,如下语法所示 −

yourStringValue.replace(/\D|^0+/g, ""))

假设以下变量包含数字 −

var theValue1="5001000";
var theValue2="100000005";
var theValue3="05000001";
var theValue4="00000000006456";

示例

var theValue1="5001000";
var theValue2="100000005";
var theValue3="05000001";
var theValue4="00000000006456";
console.log(theValue1.replace(/\D|^0+/g, ""));
console.log(theValue2.replace(/\D|^0+/g, ""));
console.log(theValue3.replace(/\D|^0+/g, ""));
console.log(theValue4.replace(/\D|^0+/g, ""));

要运行以上程序,您需要使用以下命令 −

node fileName.js.

输出

此处,我的文件名是 demo101.js。这将产生以下输出 −

PS C:\Users\Amit\JavaScript-code> node demo101.js
5001000
100000005
5000001
6456

更新时间:2020 年 9 月 7 日

916 次浏览

开启您的 职业生涯

完成该课程并获得认证

入门
广告
© . All rights reserved.