1

I use the following javascript with regex to test url string.

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

But this regex doesnt include the querystring. How can I do that?

Henrik Andersson
  • 45,354
  • 16
  • 98
  • 92
Nils Anders
  • 4,212
  • 5
  • 25
  • 38

1 Answers1

0

Perhaps you could match a string with something like this and construct from it what you want.

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

You can play with this code on jsfiddle

Xotic750
  • 22,914
  • 8
  • 57
  • 79