ceth
ceth

Reputation: 45295

split() in javascript

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?

Upvotes: 6

Views: 13435

Answers (7)

Henry H
Henry H

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

Sarfraz
Sarfraz

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

jerjer
jerjer

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

Guffa
Guffa

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

Pranay Rana
Pranay Rana

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

WaiLam
WaiLam

Reputation: 1007

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

Upvotes: 0

g.geloso
g.geloso

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

Related Questions