Javascript how to remove leading zero from a string number
- Admin
- Mar 10, 2024
- Javascript
You can check my other post on Javascript check substring exists in a String
Trim the leading zero from a number in javascript
Suppose you have a number or string such as 01, 003, and the output is 1,3. How do you trim the leading zero from a string?
There are several ways to trim leading zeros from string numbers in javascript.
- Using regular expression in the replace method
- parseInt() and parseFloat() method
Use String.replace()method
String provides replace() method to replace the pattern with the new value. Patterns might be plain strings or regular expressions.
provide regular expression with replace () method in string.
var strNumber = "0049";
console.log(typeof strNumber); //string
var number = strNumber.replace(/^0+/, "");
console.log(typeof number); //number
console.log(number); //49
pattern ^0
contains a character to match zero or more, that means leading zero at the beginning of the string and replaces it with an empty string.
Use Number constructor
if the given string contains leading zeros, return the number by truncating zero using the Number constructor.
var strNumber = "00012";
var number = Number(strNumber);
console.log(number); //12
Another way is using multiply the string by 1
var strNumber = "00034";
console.log(typeof strNumber); //string
var number = strNumber * 1;
console.log(typeof number); //number
console.log(number);// 34;
Another way use parseInt() method if the string contains leading zer integer number, Then, use parseInt
method to convert it to number by trimming leading zeroes
var strNumber = "000324";
console.log(typeof strNumber); //string
var number = parseInt(strNumber);
console.log(typeof number); //number
console.log(number); //324
if the given string number is a floating value, use the parseFloat()
method as below
var strNumber = "000124.12";
console.log(typeof strNumber); //string
var number = parseFloat(strNumber);
console.log(typeof number); //number
console.log(number); //124.12
Conclusion
Learned multiple ways to remove leading zeros from a string number in Javascript
- Use Number constructor
- Use parseInt() method
- Use parseFloat() method
- Use the String.replace() method