Wednesday, March 18, 2020

Javascript example - remove leading zero from a string of number

Delete leading zero from a number in javascript 


  Suppose if you have a number or string like 01, 003, 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.
trim leading zero 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 the zero at the beginning of the string and replace it with an empty string.

Removing leading zero from string using Number constructor

 if given string contain leading zeros, return number by truncating zero using Number constructor.
var strNumber = "00012";
var number = Number(strNumber);
console.log(number); //12
And another way is using multiply 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 a number of 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 given string number is floating value, use 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

Related article


EmoticonEmoticon