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

时间:2010-12-18 14:19:42

标签: javascript regex

我对正则表达式知之甚少,但我有一个字符串(url),我想从中提取日期:

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

我想从中提取2010/07/06,另外我希望将其格式化为6th of July, 2010

3 个答案:

答案 0 :(得分:3)

不需要正则表达式。 split()slice()的组合也可以:

var myurl = "https://example.com/display/~test/2010/07/06/Day+2.+Test+Page";
var parts = myurl.split("/");  // ["https:", "", "example.com", "display", "~test", "2010", "07", "06", "Day+2.+Test+Page"]
var ymd   = myurl.slice(5,8);  // ["2010", "07", "06"]
var date  = new Date(ymd);     // Tue Jul 06 2010 00:00:00 GMT+0200 (W. Europe Daylight Time)

有几个全面的日期格式库,我建议你选择其中一个,不要尝试自己动手。

答案 1 :(得分:2)

根据网址的更改方式,您可以使用以下内容:

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

以上将提取/2010/07/06/(两个斜杠只是为了更安全 - 您可以删除标题并尾随\/以获得2010/07/06,但如果网址包含,则可能会出现问题其他可能匹配的部分)。

请参阅此处的在线regexp示例:

这是jsfiddle:

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

这些内容(注意你需要上面的功能):

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

答案 2 :(得分:1)

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

var re = /(\d{4})\/(\d{2})\/(\d{2})/
var months = ["","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];

var parts = myurl.match(re)

var year = parseInt(parts[1]);
var month = parseInt(parts[2],10);
var day = parseInt(parts[3],10);

alert( months[month] + " " + day + ", " + year );