Reputation: 3177
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.
Upvotes: 6
Views: 7492
Reputation: 4271
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)
Upvotes: 13
Reputation: 19090
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);
Upvotes: 3