admin管理员组文章数量:1401940
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 = "+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
.
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./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
.
3 Answers
Reset to default 3Regex not required. A bination of split()
and slice()
will do as well:
var myurl = "https://example./display/~test/2010/07/06/Day+2.+Test+Page";
var parts = myurl.split("/"); // ["https:", "", "example.", "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 prehensive 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:
- http://rubular./r/bce4IHyCjW
Here's the jsfiddle:
- http://jsfiddle/zwkDQ/
To format it, take a look e.g. here:
- http://blog.stevenlevithan./archives/date-time-format
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./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 );
本文标签: regexjavascript extract date via regular expressionStack Overflow
版权声明:本文标题:regex - javascript extract date via regular expression - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744310480a2600003.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论