Alex Borsody
Alex Borsody

Reputation: 2040

window.location stored to a variable causing errors

consider the following javascript

var str=window.location;
newArray=str.split('/');
document.write(newArray[0]);

When I execute split on "var url" which holds "window.location" it is causing this error in firebug console

TypeError
arguments: Array[2]
message: "—"
stack: "—"
type: "undefined_method"
__proto__: Error

Upvotes: 2

Views: 633

Answers (3)

alex
alex

Reputation: 490123

window.location is an Object (so it has no split() method). split() is a method of a String.

You need to use window.location.href or window.location.toString() (or use it in a String context so its coerced to a String).

You may also be wanting to split on the path only, in which case you should use location.pathname. You can then use substr(1) to drop the leading / (which would only split to an empty string anyway with split('/')).

Upvotes: 0

jfriend00
jfriend00

Reputation: 707148

window.location is an object. If you want just the URL, use window.location.href.

Upvotes: 1

Robin Maben
Robin Maben

Reputation: 23034

What you need is the string that contains the url.

window.location.href

Upvotes: 3

Related Questions