Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
740 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...