如何使用JavaScript匹配我所在窗口的当前URL内的字符串?

Jan*_*nis 6 javascript regex url pattern-matching

我使用了优秀的gskinner.com/RegExr/工具来测试我的字符串匹配正则表达式,但我无法弄清楚如何将这个实现到我的JavaScript文件中以返回true或false.

我的代码如下:

^(http:)\/\/(.+\.)?(stackoverflow)\.
Run Code Online (Sandbox Code Playgroud)

在这样的网址上http://stackoverflow.com/questions/ask会匹配(根据RegExr)http://stackoverflow.

所以这很好,因为我想尝试将当前匹配window.location到该字符串,但我遇到的问题是这个JavaScript脚本不起作用:

var url = window.location;
if ( url.match( /^(http:)\/\/(.+\.)?(stackoverflow)\./ ) ) 
{
    alert('this works');
};
Run Code Online (Sandbox Code Playgroud)

我在这里做错了什么想法?

谢谢阅读.

Jannis

paw*_*wel 3

如果你想测试域名(主机)window.location.host给你你需要的(带子域名)

if( /^(.*\.)?stackoverflow\./.test(window.location.host) ){
    alert('this works');
}
Run Code Online (Sandbox Code Playgroud)