简体   繁体   中英

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 .

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.

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

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

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:

Here's the jsfiddle:

To format it, take a look eg 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
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 );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM