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.
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.
Share Improve this question asked Dec 20, 2016 at 15:48 insideinside 3,17712 gold badges51 silver badges76 bronze badges 3- 1 not plete duplicate and don't flag Remove leading zeroes in datestring – Mahi Commented Dec 20, 2016 at 15:50
-
1
Apart from missing
g
flag, the^
doesn't mean "start of" when used inside[]
. – Álvaro González Commented Dec 20, 2016 at 15:54 -
You could replace
[^\/]
with\/
, but mbomb007's answer is better as it supports any separator, not just "/". ;-) – RobG Commented Dec 20, 2016 at 20:33
2 Answers
Reset to default 13Replace \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)
You can use String.prototype.replace() and regular expression to replace the zero at the binning and the zero before /
like this:
var d = '01/02/2016'.replace(/(^|\/)0+/g, '$1');
console.log(d);