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

How can I extract values from URL string in JavaScript?

本文关键字:URL 字符串 提取 中的 JavaScript      更新时间:2023-09-26

我有一个这样的字符串:

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

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

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

我该怎么做呢?

可以使用正则表达式。下面是一个示例解决方案:

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];

如果url总是相同的格式,则执行

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);
演示