简体   繁体   中英

Why is this simple javascript not working?

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?

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM