tags:

views:

102

answers:

3

I'm finding it impossible to search for a particular value within the Address Bar.

var str = window.location;
//var str = "http://www.website.com/78203/";

var x = str.search(/78203/i);

alert(x);

The above code returns nothing, and in fact kills the running of anything else (indicating an error) but nothing is thrown in the console.

If you remove the comment, it runs fine, returning a value of more than -1 (meaning it's found something).

This is obviously something I'm not understanding correctly, can someone help me out?

+5  A: 

You should use window.location.href, because window.location is an object, not a string, and it has a search property, which contains the part of the URL that follows the ? symbol, including the ? symbol.

var str = window.location.href;

var x = str.search(/78203/i);

You can also use the String.indexOf function:

var str = window.location.href;

var x = str.indexOf('78203');

They both will return you the character position of the first occurrence of the searched string (or pattern), and if the value is not found, it will return you -1.

CMS
yeah! that works great, what was the problem with using Search - it worked fine with a manual String.
jakeisonline
there's nothing wrong with search, the problem is that you weren't searching a string
JacobM
As CMS said, window.location is an object with a "search" property. You were accessing that instead of String's property.
Pablo
+1  A: 

window.location is an object, and search is only a method of strings, so it needs to be converted to a string before you can do anything string-y with it.

var str = window.location.toString();

var x = str.search(/78203/i);
etheros
I actually realised it was probably something other than a string, so tried this method - but it didn't seem to work for me.
jakeisonline
+2  A: 

window.location is actually a Location object, not a string. What happens if you replace your code with var str = window.location.href?

Tinister