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

3 Answers 3

Reset to default 5

You 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