Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

ลบศูนย์นำหน้าตัวเลขด้วย Regex ใน JavaScript

ใช้ replace() กับ Regex /\D|^0+/g ลบอักขระไม่ใช่ตัวเลขและศูนย์นำหน้า

ตัวอย่างโค้ด

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 (เช่น node demo101.js)

ผลลัพธ์

5001000
100000005
5000001
6456