Javascript how to remove leading zero from a string number

You can check my other post on Javascript check substring exists in a String

Delete the leading zero from a number in javascript

Suppose you have a number or string like 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

Regular expression with String.replace()method

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

^0 character enables to match of the zero at the beginning of the string and replacing it with an empty string.

Removing leading zero from string using 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

And 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;

use parseInt() method
if the string contains many integers, no floating value

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