How to use Regular Expression In Javascript
This approach employs a regular expression to match and remove leading zeros from the input string. The regex pattern ^0+ matches one or more zeros at the beginning of the string. The replace() function replaces the matched pattern with an empty string, effectively removing the leading zeros.
Syntax:
stringName.replace(/^0+/, ");
Example: The below code example uses the regular expression to remove leading zeros in JavaScript.
function removeLeadingZerosRegex(str) {
return str.replace(/^0+(?=\d)/, '');
}
console.log
(removeLeadingZerosRegex("0000123"));
console.log
(removeLeadingZerosRegex("000000"));
console.log
(removeLeadingZerosRegex("0000100"));
Output
123 0 100
JavaScript Program to Remove Leading Zeros
Leading zeros are zeros that appear at the beginning of a numeric string and do not affect its value but might be undesirable in certain contexts, such as when formatting or comparing numbers.
Below are the approaches to remove leading zeros in JavaScript:
Table of Content
- Using Regular Expression
- Using JavaScript Loops
- Using Number() Constructor with toString() method
Contact Us