xivo
xivo

Reputation: 2054

Trying to match url pathname with RegEx

I'm trying to match this:

/Wedding to /Wedding/Areas

/Wedding being the word to match.

I think I'm not escaping the character correctly.

var pattern = new RegExp("^/" + href + "*$");

This is how I'm dynamically forming the test. Any help would be welcomed.

I think this would help more. I'm trying to match URLs to add a class for the current pages and sub-pages

var activePage = window.location.pathname;

$("#nav li a").each(function () {
    var href = $(this).attr("href");

    // var pattern = new RegExp("^/" + href + "/\\.*$");
    var pattern = new RegExp("^/" + href + ".*$")

    if (pattern.test(activePage)) {
        $(this).addClass("active");
    }
});

EDIT:

This is the solution I found alternatively to the RegEx. Can anyone figure out another way to solve this with RegEx?

var activePage = window.location.pathname;

$("#nav li a").each(function () {
    var href = $(this).attr("href");
    if (window.location.pathname.indexOf(href) == 0) {
        if (href != "/") {
            $(this).addClass("active");
        }
        if (href == "/" && activePage == href) {
            $(this).addClass("active");
        }
    }
});

Upvotes: 1

Views: 5452

Answers (2)

Anthony R
Anthony R

Reputation: 173

You can use the following regex to match the path name portion of a url:

var pathNameRegex = /^(?:(?:\w{3,5}:)?\/\/[^\/]+)?(?:\/|^)((?:[^#\.\/:?\n\r]+\/?)+(?=\?|#|$|\.|\/))/;


var matches = "https://stackoverflow.com/questions/9946435/trying-to-match-url-pathname-with-regex?rq=1".match(pathNameRegex);
//The last next of matches will have "questions/9946435/trying-to-match-url-pathname-with-regex"
console.log(matches[matches.length - 1]);

   matches = "/questions/9946435/trying-to-match-url-pathname-with-regex?rq=1".match(pathNameRegex);
//The last next of matches will have "questions/9946435/trying-to-match-url-pathname-with-regex"
console.log(matches[matches.length - 1]);

   matches = "//stackoverflow.com/questions/9946435/trying-to-match-url-pathname-with-regex?rq=1".match(pathNameRegex);
//The last next of matches will have "questions/9946435/trying-to-match-url-pathname-with-regex"
console.log(matches[matches.length - 1]);

Upvotes: 1

Jerome Cance
Jerome Cance

Reputation: 8183

var pattern = new RegExp("^/" + href + ".*$");

you forget the dot before the asterisk

but a better regex would be :

"^/" + href + "/.*$"

to be sure to have a subpath and not a partial word

Upvotes: 3

Related Questions