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

时光总嘲笑我的痴心妄想 提交于 2019-12-07 02:35:27

问题


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.

The code I have is as follows:

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

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

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?

Thanks for reading.

Jannis


回答1:


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');
}



回答2:


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



来源:https://stackoverflow.com/questions/2522532/how-can-i-use-javascript-to-match-a-string-inside-the-current-url-of-the-window

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!