Search code examples
javascriptstringgreasemonkeyuserscripts

How can I extract values from URL string in JavaScript?


I have a string like this:

http://x.com/xyz/2013/01/16/zz/040800.php

I want to get two strings from that, like this:

2013-01-16 <-- string 1
04:08:00 <-- string 2

How can I do that?


Solution

  • If the url is always of the same format, do this

    var string = 'http://x.com/xyz/2013/01/16/zz/040800.php';
    
    var parts = string.split('/');
    
    var string1 = parts[4] +'-' +parts[5] +"-" +parts[6];
    var string2 = parts[8][0]+parts[8][1] +":" +parts[8][2]+parts[8][3] +":" +parts[8][4]+parts[8][5];
    
    alert(string1);
    alert(string2);
    

    DEMO