Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/459.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 正在尝试将url路径名与正则表达式匹配_Javascript_Regex - Fatal编程技术网

Javascript 正在尝试将url路径名与正则表达式匹配

Javascript 正在尝试将url路径名与正则表达式匹配,javascript,regex,Javascript,Regex,我正在尝试匹配以下内容: /Wedding至/Wedding/Areas /widding是要匹配的词 我想我没有正确地避开这个角色 var pattern = new RegExp("^/" + href + "*$"); 这就是我动态形成测试的方式。欢迎任何帮助 我想这会更有帮助。我正在尝试匹配URL,为当前页面和子页面添加一个类 var activePage = window.location.pathname; $("#nav li a").each(function () {

我正在尝试匹配以下内容:

/Wedding
/Wedding/Areas

/widding
是要匹配的词

我想我没有正确地避开这个角色

var pattern = new RegExp("^/" + href + "*$");
这就是我动态形成测试的方式。欢迎任何帮助

我想这会更有帮助。我正在尝试匹配URL,为当前页面和子页面添加一个类

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

这是我找到的替代正则表达式的解决方案。有人能想出另一种方法来解决这个问题吗

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");
        }
    }
});
你忘了星号前的点

但更好的正则表达式是:

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

为了确保有子路径而不是部分单词,可以使用以下正则表达式匹配url的路径名部分:

var-pathNameRegex=/^(?:(?:\w{3,5}:)?\/\/[^\/]+)(?:\/\/^)((?:[^\.\/:?\n\r]+\/?)+(?=?=?| | |$.\/)/;
变量匹配=”https://stackoverflow.com/questions/9946435/trying-to-match-url-pathname-with-regex?rq=1“.match(pathNameRegex);
//最后一个匹配项将有“疑问/9946435/尝试将url路径名与正则表达式匹配”
log(匹配[matches.length-1]);
matches=“/questions/9946435/尝试将url路径名与regex匹配?rq=1”。匹配(路径名regex);
//最后一个匹配项将有“疑问/9946435/尝试将url路径名与正则表达式匹配”
log(匹配[matches.length-1]);
matches=“//stackoverflow.com/questions/9946435/尝试将url路径名与regex?rq=1匹配”。匹配(pathNameRegex);
//最后一个匹配项将有“疑问/9946435/尝试将url路径名与正则表达式匹配”

log(匹配[matches.length-1])为什么要转义圆点?转义
与圆点完全匹配。它应该是
var pattern=newregexp(“^/”+href+“*$”)
oops,对不起。一天的结束。需要睡觉;)。。。或者干脆完全忘记
$
"^/" + href + "/.*$"