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
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 );
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 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
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.