admin 管理员组文章数量: 1086019
I'm unable to find a way to remove date ordinals while preserving the month in a string.
For example, I would need:
June 12th, 2015
To output to:
June 12, 2015
I've found this post that mentions how to do it, but that form of RegEx does not work with JavaScript.
I'm unable to find a way to remove date ordinals while preserving the month in a string.
For example, I would need:
June 12th, 2015
To output to:
June 12, 2015
I've found this post that mentions how to do it, but that form of RegEx does not work with JavaScript.
Share Improve this question edited May 23, 2017 at 10:27 CommunityBot 11 silver badge asked Jan 31, 2016 at 6:10 webdevborninthe90swebdevborninthe90s 391 silver badge3 bronze badges 3- Are you using moments library? – Avinash Commented Jan 31, 2016 at 6:11
-
Use
.replace(/(\d+)(?:st|nd|rd|th)/, "$1")
– Tushar Commented Jan 31, 2016 at 6:11 - Is the input always just a date, or could it be an entire sentence that happened to contain a date? – user663031 Commented Jan 31, 2016 at 12:31
3 Answers
Reset to default 5You need to create two capturing group, to select both the number of month (\d+)
and its ordinal (st|nd|rd|th)
. Then replace the string with $1
(first group which is containing the number of month). Something like this:
var str = "June 12th, 2015";
str.replace(/(\d+)(st|nd|rd|th)/, "$1");
//=> June 12, 2015
Live Demo
If you want to use RegEx:
ord_day_pattern = re.pile(r"(?<=\d)(st|nd|rd|th)")
print re.pile(ord_day_pattern).sub("", mystring)
One-liner:
print re.pile(r"(?<=\d)(st|nd|rd|th)").sub("", mystring)
If you don't want to worry about the various ordinals you could use a regex to match any 2 characters preceding a ,
. The regex to use would be:
var regex= /[a-z]{2},/;
which matches a string of 2 characters followed by a ,
.
For example:
> var regex= /[a-z]{2},/;
> var dateStr = 'June 12th, 2015';
> dateStr.replace(regex, ',');
< 'June 12, 2015'
本文标签: javascriptHow to remove Date Ordinals (st nd RD th)Stack Overflow
版权声明:本文标题:javascript - How to remove Date Ordinals (st, nd, rd, th) - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.roclinux.cn/p/1741834023a2317809.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论