javascript extract date via regular expression

前端 未结 3 1575
说谎
说谎 2020-12-12 02:30

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         


        
3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-12 03:31

    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.

提交回复
热议问题