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

I used the great tool gskinner.com/RegExr/ to test the regular expression for a string, but I cannot figure out how to implement this in my JavaScript file to return true or false.

The code I have is as follows:

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

on the url, e.g. http://stackoverflow.com/questions/ask , this will match (according to RegExr) http://stackoverflow.

So, this is great, because I want to try matching the current window.location with this line, but the problem I am facing is that this JavaScript script is not working:

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

Any ideas on what I'm doing wrong here?

Thanks for reading.

Jannis

+6
javascript url regex pattern-matching
source share
2 answers

If you want to check the domain name (host) of window.location.host , you will get what you need (with a subdomain)

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

window.location not a string; this is an object. Use window.location.href

+3
source share

All Articles