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

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

Answers


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

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


Need Your Help

How is that instance pooling with EJBs can improve performance?

performance java-ee ejb pooling

How is that instance pooling with EJBs can improve performance? Wouldn't you be able to accomplish the same performance just with threads like a java servlet?

Can't figure out why bootstrap navbar collapse toggle isn't working

twitter-bootstrap-3

I copy and pasted the bootstrap navbar into codepen but I can't get any of the dropdown navbars to work. I'm trying to make a webpage where when viewed in mobile, you can use the dropdown button to