最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Remove zeros from Date string - Stack Overflow

programmeradmin6浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 13

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)

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);

发布评论

评论列表(0)

  1. 暂无评论