Javascript 正则表达式 URL 匹配

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2838404/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:07:31  来源:igfitidea点击:

Javascript regex URL matching

javascriptregexjavascript-events

提问by BonjourHolaOla

I have this so far:

到目前为止我有这个:

chrome.tabs.getSelected(null, function(tab) 
{
    var title = tab.title;
    var btn = '<a href="' + tab.url + '" onclick="save(\'' + title + '\');"> ' + title + '</a>';

    if(tab.url.match('/http:\/\/www.mydomain.com\/version.php/i')) 
    {
        document.getElementById('link').innerHTML = '<p>' + btn + '</p>';
    }
});

Basically it should match the domain within this:

基本上它应该与以下域匹配:

http://www.mydomain.com/version.php?*

Anything that matches that even when it includes something like version.php?ver=1, etc

任何匹配的内容,即使它包含诸如 version.php?ver=1 之类的内容

When I used the code above of mine, it doesn't display anything, but when I remove the if statement, it's fine but it shows on other pages which it shouldn't onlyon the matched URL.

当我使用我上面的代码时,它没有显示任何内容,但是当我删除 if 语句时,它可以显示在其他页面上,而它不应该显示在匹配的 URL 上。

EDIT:

编辑:

if(tab.url.match(/http:\/\/www.mydomain.com\/version.php/i)) 
{
    document.getElementById('link').innerHTML = '<p>' + btn + '</p>';
}

Doesn't even work somehow...

甚至不以某种方式工作...

采纳答案by limc

Try this

尝试这个

if(tab.url.match(/http\:\/\/www\.mydomain\.com\/version\.php/i)) 
{
    //...
}

回答by Artefacto

Remove the quotes. Opera DargonFly gives me:

删除引号。Opera DargonFly 给了我:

>>> 'http://www.mydomain.com/version.php'.match(/^http:\/\/www\.mydomain.com\/version\.php/i) 
[object Array]

回答by Arkku

match()should take a RegExpobject as argument, not a string. You could probably just remove the single quotes ''from around the expression to make it work. For future reference, you should also escape the periods .in the expression (as it is they will match anysingle character), and insert a ^in the beginning to only allow this match in the beginning of the URL.

match()应该将一个RegExp对象作为参数,而不是一个字符串。您可能只需''从表达式中删除单引号即可使其工作。为了将来参考,您还应该.对表达式中的句点进行转义(因为它们将匹配任何单个字符),并^在开头插入 a以仅允许在 URL 的开头进行此匹配。

回答by Artefacto

You are creating the RegExp object, but you're not matching it against anything. See herefor how to use it (by the way, the syntax is also wrong, it's either /expression/modifiers or RegExp(expression, modifiers)).

您正在创建 RegExp 对象,但您没有将它与任何内容进行匹配。看这里如何使用它(顺便说一句,语法也是错误的,要么是 /expression/modifiers 要么是 RegExp(expression, modifiers))。