Was it helpful?

Question

JavaScript Regex to remove leading zeroes from numbers?

JavascriptWeb DevelopmentObject Oriented Programming

To remove leading zeros, use Regex in replace() method as in the below syntax −

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

Let’s say the following are our variables with number values −

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

Example

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, ""));

To run the above program, you need to use the following command −

node fileName.js.

Output

Here, my file name is demo101.js. This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo101.js
5001000
100000005
5000001
6456
raja
Published on 07-Sep-2020 12:12:37
Advertisements
Was it helpful?
Not affiliated with Tutorialspoint
scroll top