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

时间:2021-08-21 06:40:30

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.

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

The code I have is as follows:

我的代码如下:

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

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

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

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:

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

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

Any ideas on what I am doing wrong here?

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

Thanks for reading.

谢谢阅读。

Jannis

Jannis

2 个解决方案

#1


2  

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

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

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

#2


3  

window.location is not a string; it's an object. Use window.location.href

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

#1


2  

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

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

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

#2


3  

window.location is not a string; it's an object. Use window.location.href

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