'Remove zeros from Date string
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.
Solution 1:[1]
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)
Solution 2:[2]
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);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
