移除數字前導零的 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.