Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
744 views
in Technique[技术] by (71.8m points)

regex - javascript extract date via regular expression

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Regex not required. A combination of split() and slice() will do as well:

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)

There are several comprehensive date formatting libraries, I suggest you take one of those and do not try to roll your own.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...