繁体   English   中英

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

[英]How can I use JavaScript to match a string inside the current URL of the window I am in?

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

我的代码如下:

^(http:)\/\/(.+\.)?(stackoverflow)\.

在诸如http://stackoverflow.com/questions/ask的URL上,这将匹配(根据RegExr) http://stackoverflow.

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

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

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

谢谢阅读。

Jannis

window.location不是字符串; 这是一个对象。 使用window.location.href

如果你想测试域名(主机) window.location.host为你提供你需要的东西(使用子域名)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM