如何从JavaScript中的URL字符串中提取值?

时间:2013-01-16 14:21:54

标签: javascript string greasemonkey userscripts

我有一个这样的字符串:

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

我想从中得到两个字符串, 像这样:

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

我该怎么做?

2 个答案:

答案 0 :(得分:2)

您可以使用regularx表达式。这是一个示例解决方案:

var parts = (/.com\/[^\/]+\/(\d+)\/(\d+)\/(\d+)/g).exec('http://x.com/xyz/2013/01/16/zz/040800.php'),
    result = parts[1] + '-' + parts[2] + '-' + parts[3]; //"2013-01-16"

如果您的域名为.com并且您在日期之前只有一个额外参数,则此功能将有效。

让我向你解释一下正则表达式:

 /          //starts the regular expression
 .com       //matches .com
   \/       //matches /
   [^\/]+   //matches anything except /
      \/    //matches a single /
      (\d+) //matches more digits (one or more)
      \/    //matches /
   (\d+)    //matches more digits (one or more)
  \/        //matches /
 (\d+)      //matches more digits (one or more)
/           //ends the regular expression

以下是提取整个数据的方法:

var parts = (/.com\/[^\/]+\/(\d+)\/(\d+)\/(\d+)\/[^\/]+\/(\d+)/g).exec('http://x.com/xyz/2013/01/16/zz/040800.php'),
    part2 = parts[4];

parts[1] + '-' + parts[2] + '-' + parts[3]; //"2013-01-16"
part2[0] + part2[1] + ':' + part2[2] + part2[3] + ':' + part2[4] + part2[5];

答案 1 :(得分:1)

如果网址格式始终相同,请执行此操作

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

相关问题