1

URL文字列をテストするために、正規表現で次のjavascriptを使用します。

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");
     }
});

しかし、この正規表現にはクエリ文字列が含まれていません。どうやってやるの?

4

1 に答える 1

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でこのコードを試すことができます

于 2013-04-17T07:37:46.513 に答える