带有查询字符串的URL的正则表达式

时间:2013-04-17 07:10:19

标签: javascript jquery

我使用以下javascript和regex来测试url字符串。

var url = window.location.pathname;

// create regexp to match current url pathname and remove trailing slash if 
// present as it could collide with the link in navigation in case 
// trailing slash wasn't present there
urlRegExp = new RegExp(url == '/' ? window.location.origin + '/?$' : url.replace(/\/$/, '')); 

// now grab every link from the navigation
$('.page-sidebar a').each(function () {
    // and test its normalized href against the url pathname regexp
     if (urlRegExp.test(this.href.replace(/\/$/, ''))) {
         $(this).closest("li").addClass("active");
     }
});

但是这个正则表达式不包含查询字符串。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

也许你可以将一个字符串与这样的东西相匹配,并从中构建你想要的东西。

var rx = new RegExp("^(?:([^:\\/?#]+):)?(?:\\/\\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\\/?#]*)(?::(\\d*))?))?((((?:[^?#\\/]*\\/)*)([^?#]*))(?:\\?([^#]*))?(?:#(.*))?)");

var url = "http://stackoverflow.com/questions/16053753/regex-for-url-with-querystring?a0b&c=d&e=f#anchor";

var val = url.match(rx);

val.forEach(function (part) {
    var result = $("#result");
    var $text = $("<p>").text(part);
    result.append($text);
});

您可以在jsfiddle

上使用此代码