javascript extract date via regular expression

前端 未结 3 1566
说谎
说谎 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:07
    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 );
    
    0 讨论(0)
  • 2020-12-12 03:08

    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.com/r/bce4IHyCjW

    Here's the jsfiddle:

    • http://jsfiddle.net/zwkDQ/

    To format it, take a look e.g. here:

    • http://blog.stevenlevithan.com/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
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题