尝试将URL路径名与RegEx匹配

时间:2012-03-30 15:56:13

标签: javascript regex

我正在尝试匹配这个:

/Wedding/Wedding/Areas

/Wedding是匹配的词。

我想我并没有正确地逃避这个角色。

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

这就是我动态形成测试的方式。任何帮助都会受到欢迎。

我认为这会有所帮助。我正在尝试匹配网址以添加当前页面和子页面的类

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

`

编辑:

这是我在RegEx上找到的解决方案。任何人都可以想出用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"); } } });

2 个答案:

答案 0 :(得分:3)

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

你忘记了星号前的点

但更好的正则表达式是:

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

确保有一个子路径而不是一个部分词

答案 1 :(得分:0)

您可以使用以下正则表达式来匹配网址的路径名部分:

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