{

Javascript how to remove leading zero from a string 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.

Javascript example - remove leading zero from a string of number
  • 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 the given string contains leading zeros, return the 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 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 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  

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.