window.location.indexOf not working in Javascript
Asked Answered
W

3

11

Below is what I have.

var myString = "http://localhost:8888/www.smart-kw.com/";
alert(myString.indexOf("localhost"));

This give me alert... however if I change var myString = "http://localhost:8888/www.smart-kw.com/"; to var myString = window.location;, it won't work (I don't get alert).

var myString = window.location;
alert(myString.indexOf("localhost"));
Waterfront answered 2/12, 2012 at 12:56 Comment(1)
@MartijnPieters : Okay, I will take care of that.Waterfront
O
33

window.location is an accessor property, and getting its value gives you an object, not a string, and so it doesn't have an indexOf function. (It's perfectly understandable that people sometimes think it's a string, since when you set its value, the accessor property's setter accepts a string; that is, window.location = "some url"; actually works. But when you get it, you don't get a string.)

You can use window.location.toString(), String(window.location), or window.location.href to get a string for it if you like, or use any of its various properties to check specifics. From the link, given example url http://www.example.com:80/search?q=devmo#test:

  • hash: The part of the URL that follows the # symbol, including the # symbol. You can listen for the hashchange event to get notified of changes to the hash in supporting browsers.
    Example: #test
  • host: The host name and port number.
    Example: www.example.com:80
  • hostname: The host name (without the port number).
    Example: www.example.com
  • href: The entire URL.
    Example: http://www.example.com:80/search?q=devmo#test
  • pathname: The path (relative to the host).
    Example: /search
  • port: The port number of the URL.
    Example: 80
  • protocol: The protocol of the URL.
    Example: http:
  • search: The part of the URL that follows the ? symbol, including the ? symbol.
    Example: ?q=devmo

For instance, for your quoted example, you might check window.location.hostname === "localhost".

Ounce answered 2/12, 2012 at 12:58 Comment(0)
S
3

As far as I know window.location is a Location object.

For instance, window.location.href will give you the entire URL.

var url = window.location.href;
alert(url.indexOf("domain"));

But this kind of check is bound to trigger false-positives. You are better using window.location.hostname property which holds the host name part.

var hostname = window.location.hostname;
alert(hostname === "my.domain.com");
Substitution answered 2/12, 2012 at 12:58 Comment(0)
K
2

I found a way to make this work:

(window.location.href).indexOf("localhost") > -1)

I actually use this for my projects as conditionals and it works just fine.

Kv answered 3/3, 2016 at 16:39 Comment(1)
So weird mine wasn't working without parenthesis around window.location.href but adding that works fine! WEIRDHeteroousian

© 2022 - 2024 — McMap. All rights reserved.