Reputation: 45295
I have code:
function _filter() {
var url = window.location;
alert(url);
alert(url.split("/")[1]);
}
When I launch it I get only one alert message:
Why I don't get the second alert message?
Upvotes: 6
Views: 13435
Reputation: 103
The index [1] is in between the two slashes of http://
which is null and wont be alerted. Index [2] is the localhost:8000
you're probably looking for.
Simple window.location.hostname
should be useful too.
Upvotes: 1
Reputation: 382706
Adding .toString()
works and avoids this error:
TypeError: url.split is not a function
function _filter() {
var url = window.location;
alert(url);
alert(url.toString().split("/")[2]);
}
When run on this very page, the output is:
stackoverflow.com
Upvotes: 14
Reputation: 8770
The location object is the cause of this, window.location is an object not a string it is the location.href or location.toString().
function _filter() {
var url = window.location.href; // or window.location.toString()
alert(url);
alert(url.split("/")[1]);
}
Upvotes: 4
Reputation: 700362
The value of window.location
is not a string, you want the href
property of the location object:
function _filter() {
var url = window.location.href;
alert(url);
alert(url.split("/")[1]);
}
Upvotes: 3
Reputation: 176906
Because your url is ans object so you need to convert this to string than you apply split function
function _filter() {
var url = window.location+ '';
alert(url);
alert(url.split("/")[2]);
}
Upvotes: 1
Reputation: 1007
url.split("/")[1] will equal to null. So, it alert(null) will not display msg.
Upvotes: 0
Reputation: 159
To understand how many pieces you get from splitting operation you can alert the .lenght of url.split, are you sure that the script doesn't block?
Use firebug to understand that
Upvotes: 0