2013-04-17 96 views
1

我使用以下JavaScript與正則表達式來測試url字符串。具有查詢字符串的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"); 
    } 
}); 

但是,這個正則表達式不包括查詢字符串。我怎樣才能做到這一點?

+0

初步認識問題http://stackoverflow.com/questions/37684/how-to-replace-plain-urls-with-links/37687 – shakib

+0

HTTP玩: //stackoverflow.com/about – Xotic750

回答

0

也許你可以匹配一個字符串與這樣的東西,並從中構建你想要的。

var rx = new RegExp("^(?:([^:\\/?#]+):)?(?:\\/\\/((?:(([^:@]*)(?::([^:@]*))?)[email protected])?([^:\\/?#]*)(?::(\\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

相關問題