Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Removing 0s from start and end - JavaScript
We are required to write a JavaScript function that takes in a number as a string and returns a new number string with all the leading and trailing 0s removed.
For example: If the input is ?
const strNum = '054954000'
Then the output should be ?
const output = '54954'
Using substring() Method
This approach uses two pointers to find the first non-zero character from the start and end, then extracts the substring between them.
const strNum = '054954000';
const removeZero = (str = '') => {
let startLen = 0, endLen = str.length - 1;
// Find first non-zero character from start
while(str[startLen] === '0') {
startLen++;
}
// Find first non-zero character from end
while(str[endLen] === '0') {
endLen--;
}
return str.substring(startLen, endLen + 1);
};
console.log(removeZero(strNum));
console.log(removeZero('00012300'));
console.log(removeZero('000'));
54954 123 0
Using Regular Expressions
A more concise approach using regex to match leading and trailing zeros.
const removeZeroRegex = (str) => {
// Remove leading zeros, then trailing zeros
return str.replace(/^0+/, '').replace(/0+$/, '') || '0';
};
console.log(removeZeroRegex('054954000'));
console.log(removeZeroRegex('00012300'));
console.log(removeZeroRegex('000'));
54954 123 0
Using parseInt() and toString()
Converting to number automatically removes leading zeros, then back to string removes trailing zeros from decimal representations.
const removeZeroNumber = (str) => {
const num = parseInt(str, 10);
return num.toString();
};
console.log(removeZeroNumber('054954000'));
console.log(removeZeroNumber('00012300'));
console.log(removeZeroNumber('000'));
54954 12300 0
Comparison
| Method | Handles Trailing Zeros | Performance | Readability |
|---|---|---|---|
| substring() | Yes | Fast | Medium |
| Regular Expression | Yes | Medium | High |
| parseInt() | No | Fast | High |
Edge Cases
Handle special cases like strings containing only zeros:
const removeZeroSafe = (str) => {
let result = str.replace(/^0+/, '').replace(/0+$/, '');
return result === '' ? '0' : result;
};
console.log(removeZeroSafe('000'));
console.log(removeZeroSafe('0'));
console.log(removeZeroSafe('102030'));
0 0 10203
Conclusion
The regex approach offers the cleanest solution for removing both leading and trailing zeros. Use parseInt() only when trailing zeros don't need to be preserved.
