views:

51

answers:

2

New to js here. Basically I am trying to detect the existence of a string in the present page's url with this:

var url = window.location;
var param = /\?provider=/i;
if (url.search(param) != -1) {
    alert('it does exist');
} else
    alert('it does not exist');

It works when I manually define the url variable like so

var url = 'http://google.com?provider='

but when I try to grab it dynamically like in the above script it doesn't work, is there any way to make it work?

+2  A: 

You want the href property on the location object, like this:

var url = window.location.href;
var param = /\?provider=/i;
if (url.search(param) != -1) {
    alert('it does exist');
} else
    alert('it does not exist');

location isn't a string, it's an object, and doesn't have the .search() method, .href is the string that does.

Nick Craver
+1. You can also do `.toString()` which works on all objects.
Matthew Flaschen
A: 

window.location is an object. Have a look at the entire set of properties of the location object: https://developer.mozilla.org/en/DOM/window.location

What you're after is window.location.href;

Russell Dias