views:

125

answers:

2

Hi,

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  A: 

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

reko_t
Thanks for your help, I couldn't quite get this to work so i went with Pawel's solution, but thanks again nonetheless.
Jannis
This is good answer, too. window.location is an object, .href nad .host are its properties represented as strings. You can use any of these, but I thought location.host is better when you're only interested in this part of location string :)
pawel
ah, now it makes sense to me, so the href will return the full url whereas the host will only go as far as `http://sub.domain.ext/` ?
Jannis
Host will only return the "sub.domain.ext" part, as that is the host.
reko_t
+1  A: 

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');
}
pawel
This works great!Thank you very much.
Jannis