6

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:

http://localhost:8000/index/3/1.

Why I don't get the second alert message?

2
  • check whether url.split("/")[1] is valid statement Commented Nov 23, 2010 at 7:09
  • 2
    window.location is a non-string object. You either need to call toString() or just grab window.location.href. Commented Nov 23, 2010 at 7:12

7 Answers 7

14

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
Sign up to request clarification or add additional context in comments.

2 Comments

The location object has the href property intended just for this.
@Guffa: True href should be added with no need to use toString.
4

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]);
  }

Comments

3

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]);
}

Comments

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]);
}

Comments

1

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.

1 Comment

+1 for pointing out that the location object has other properties that could be used to get parts of the URL.
0

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

Comments

0

url.split("/")[1] will equal to null. So, it alert(null) will not display msg.

1 Comment

Yeah. the location object didn't have split function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.