split() in javascript
I have code:
function _filter() {
var url开发者_如何学Python = window.location;
alert(url);
alert(url.split("/")[1]);
}
When I launch it I get only one alert message:
http://localhost:8000/index/3/1.
Why I don't get the second alert message?
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
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]);
}
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]);
}
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]);
}
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.
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
url.split("/")[1] will equal to null. So, it alert(null) will not display msg.
精彩评论