I want to delete the first character of a string if it’s a 0. The 0 could appear multiple times at the start.
Is there a simple function to check the first character and remove it if it’s 0? I’m currently using the slice() function, but it feels a bit awkward.
What’s the best way to JavaScript remove first character from string if it’s 0?
The simplest and most efficient approach is to use a regular expression with the replace() function.
This allows you to remove leading 0s without the need for awkward slicing.
Here’s how you can do it:
function removeLeadingZero(str) {
return str.replace(/^0+/, ''); // Removes all leading zeros
}
console.log(removeLeadingZero("000123")); // Outputs: "123"
Why this works? The ^0+ regex matches one or more zeros at the start of the string (^ indicates the start). This solution is clean and does the job in one line.
If you prefer to stick with slice() but want to make the operation more explicit, you can use a loop to iteratively remove the leading 0s.
This is a more manual approach but can be useful if you need fine control over the string.
function removeLeadingZero(str) {
while (str.charAt(0) === '0') {
str = str.slice(1);
}
return str;
}
This approach keeps the slice() function but ensures you handle multiple leading zeros in a more controlled manner.
If you’re feeling adventurous and want to ensure only the first occurrence of 0 is removed (for cases like “01230”), you can use a custom function with replace():
function removeLeadingZero(str) {
return str.replace(/^0/, ''); // Removes only the first leading zero
}
console.log(removeLeadingZero("01230")); // Outputs: "1230"
This version handles only the first leading zero and leaves the others intact. It’s great for cases where you want to remove a specific zero but not all leading zeros.