Possible Duplicate:
Truncate leading zeros of a string in Javascript
What is the simplest and cross-browser compatible way to remove leading zeros from a number in Javascript ?
e.g. If I have a textbox value as 014 or 065, it should only return 14 or 65
Use parseInt() to remove leading zeros from a number in JavaScript.
Use the inbuilt replaceAll() method of the String class which accepts two parameters, a Regular Expression, and a Replacement String. To remove the leading zeros, pass a Regex as the first parameter and empty string as the second parameter. This method replaces the matched value with the given string.
Approach: Mark the first non-zero number's index in the given array. Store the numbers from that index to the end in a different array. Print the array once all numbers have been stored in a different container.
We can use four methods for this conversion
10 const numString = "065";    //parseInt with radix=10  let number = parseInt(numString, 10);  console.log(number);    // Number constructor  number = Number(numString);  console.log(number);    // unary plus operator  number = +numString;  console.log(number);    // conversion using mathematical function (subtraction)  number = numString - 0;  console.log(number);  For the primitive type Number, the safest max value is 253-1(Number.MAX_SAFE_INTEGER). 
console.log(Number.MAX_SAFE_INTEGER);  Now, lets consider the number string '099999999999999999999' and try to convert it using the above methods
const numString = '099999999999999999999';    let parsedNumber = parseInt(numString, 10);  console.log(`parseInt(radix=10) result: ${parsedNumber}`);    parsedNumber = Number(numString);  console.log(`Number conversion result: ${parsedNumber}`);    parsedNumber = +numString;  console.log(`Appending Unary plus operator result: ${parsedNumber}`);    parsedNumber = numString - 0;  console.log(`Subtracting zero conversion result: ${parsedNumber}`);  All results will be incorrect.
That's because, when converted, the numString value is greater than Number.MAX_SAFE_INTEGER. i.e.,
99999999999999999999 > 9007199254740991   This means all operation performed with the assumption that the stringcan be converted to number type fails.
For numbers greater than 253, primitive BigInt has been added recently. Check browser compatibility of BigInthere. 
The conversion code will be like this.
const numString = '099999999999999999999'; const number = BigInt(numString);   parseInt?If radix is undefined or 0 (or absent), JavaScript assumes the following:
Exactly which radix is chosen is implementation-dependent. ECMAScript 5 specifies that 10 (decimal) is used, but not all browsers support this yet.
For this reason, always specify a radix when using parseInt
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With