如何使用JavaScript匹配我所在窗口的当前URL内的字符串? [英] How can I use JavaScript to match a string inside the current URL of the window I am in?

查看:111
本文介绍了如何使用JavaScript匹配我所在窗口的当前URL内的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have used the excellent gskinner.com/RegExr/ tool to test my string matching regex but I cannot figure out how to implement this into my JavaScript file to return true or false.

我的代码如下:

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

在网址上,例如 http://stackoverflow.com/questions/询问这将匹配(根据RegExr) http:// stackoverflow。

on a url such as http://stackoverflow.com/questions/ask this would match (according to RegExr) http://stackoverflow.

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

So this is great because I want to try matching the current window.location to that string, but the issue I am having is that this JavaScript script does not work:

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

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

Any ideas on what I am doing wrong here?

感谢您的阅读。

Jannis

推荐答案

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

If you want to test domain name (host) window.location.host gives you what you need (with subdomain)

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

这篇关于如何使用JavaScript匹配我所在窗口的当前URL内的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆