jquery匹配URL self.location.href中的确切字符串

时间:2015-01-22 22:36:22

标签: jquery

我目前正在使用以下行来匹配此网址 - www.sitename.com/join

if(/join/.test(self.location.href)) {joinPopUp();}

抓住它也会匹配/ blahjoinblah。

如何更改此内容,以便只匹配确切的字词' join'。

注意:我认为必须匹配' / join'作为' /'仍然存在(我认为)。

三江源

2 个答案:

答案 0 :(得分:1)

正则表达式\/join(?=\/)可能正是您要找的。它会检查/join值,然后使用positive look-a-head查看字符/是否跟随。

在控制台内进行快速测试:

["/xxjoin", "/join/", "/joinme", "joinme"].
          forEach(function (value) { 
                     console.log(value.match(/\/join(?=\/)/));
                  });

// returns the following:

null
["/join", index: 0, input: "/join/"]
null 
null

或为了便于阅读,

["/xxjoin", "/join/", "/joinme", "joinme"].
          filter(function(v) { 
                    return v.match(/\/join(?=\/)/) != null;
                 });

// returns ['/join/']

答案 1 :(得分:1)

要了解有关正则表达式的更多信息,请阅读其中一些great resources

但是要更具体地回答你的问题,如果你真的希望它只匹配/join没有查询字符串变量或其他输入,那么像这样的东西可以检查/和那个它以/join结尾。虽然我认为它仍然匹配/foo/join

function testUrl(url) {
    if(/\/join\/?$/.test(url)) {
        console.log(url, "matched /join");
    }
}

testUrl(self.location.href);
testUrl("https://test.com/join");
testUrl("https://test.com/foo/join");
testUrl("http://test.com/blahjoinblah"); 

所以你可能想要改变你所匹配的内容 - 可能会看self.location.pathname

相关问题