javascript通过正则表达式提取日期

javascript通过正则表达式提取日期

本文介绍了javascript通过正则表达式提取日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对正则表达式了解不多,但是我有一个字符串(url),我想从中提取日期:

I don't know much about regular expressions, but I got a string (url) and I'd like to extract the date from it:

var myurl = "https://example.com/display/~test/2010/07/06/Day+2.+Test+Page";

我想从中提取 2010/07/06 ,此外,我想将其格式设置为 2010年7月6日.

I'd like to extract 2010/07/06 from it, additionally I would like to have it formatted as 6th of July, 2010.

推荐答案

根据URL的更改方式,您可以使用类似以下的内容:

Depending on how the URL can change, you can use something like:

\/\d{4}\/\d{2}\/\d{2}\/

上面的代码将提取/2010/07/06/(为了更安全,两个斜杠-您可以删除标题和结尾的 \/以获得 2010/07/06 ,但如果URL包含其他可能匹配的部分,则可能会出现问题.

The above will extract /2010/07/06/ (the two slashes just to be safer - you can remove the heading and trailing \/ to get just 2010/07/06, but you might have issues if URL contains other parts that may match).

在此处查看在线正则表达式示例:

See the online regexp example here:

这是jsfiddle:

Here's the jsfiddle:

要格式化,请看例如在这里:

To format it, take a look e.g. here:

遵循这些原则(请注意,您需要上面的功能):

Something along these lines (note you need the function from above):

var dt = new Date(2010, 6, 6);
dateFormat(dt, "dS of mmmm, yyyy");
// 6th of June, 2010

这篇关于javascript通过正则表达式提取日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 21:57