如何使用JavaScript RegExp匹配特定的URL

时间:2012-08-21 14:57:12

标签: javascript regex

我正在尝试使用RegExp匹配此部分网址:

/l.php?u=http%3A%2F%2Fwww.transmoto.com.au%2Fpublish%2Fnews%2F14614708%2FBopping%2C-Styke-and-Waters-to-lead-Team-Australia-at-MXoN&h=5AQEDldxs&s=1

理想情况下,我需要匹配'u'值并将其转换为正确的url(即将%3A替换为:和%2F替换为/),但我很高兴只匹配整个表达式。

我尝试过多种RegExp组合,但没有取得任何成功。

2 个答案:

答案 0 :(得分:0)

尝试:

var match = url.match(/u=([^&]+)/);

/* Alerts http%3A%2F%2Fwww.transmoto.com.au%2Fpublish%2Fnews%2F14614708
   %2FBopping%2C-Styke-and-Waters-to-lead-Team-Australia-at-MXoN */
alert(match[1]);

/* Alerts http://www.transmoto.com.au/publish/news/14614708/Bopping,-Styke
  -and-Waters-to-lead-Team-Australia-at-MXoN */
alert(decodeURIComponent(match[1]);

答案 1 :(得分:0)

var url = '/l.php?u=http%3A%2F%2Fwww.transmoto.com.au%2Fpublish%2Fnews%2F14614708%2FBopping%2C-Styke-and-Waters-to-lead-Team-Australia-at-MXoN&h=5AQEDldxs&s=1';
var re = url.match(/\?(?:|.*?&)u=([^&]+)/);

这是jsFiddle