I have a string with the following format: '01/02/2016' and I am trying to get rid of the leading zeros so that at the end I get '1/2/2016' with regex.
Tried '01/02/2016'.replace(/^0|[^\/]0./, '');
so far, but it only gives me 1/02/2016
Any help is appreciated.
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.
Your answerIf you add a hyphen between the % and the letter, you can remove the leading zero. For example %Y/%-m/%-d. This only works on Unix (Linux, OS X), not Windows. On Windows, you would use #, e.g. %Y/%#m/%#d.
Replace \b0
with empty string. \b
represents the border between a word character and a non-word character. In your case, \b0
will match a leading zero.
var d = '01/02/2016'.replace(/\b0/g, '');
console.log(d); // 1/2/2016
var d = '10/30/2020'.replace(/\b0/g, '');
console.log(d); // 10/30/2020 (stays the same)
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