jeffreynolte
jeffreynolte

Reputation: 3779

indexOf always returning true for document.location

I have the following script:

if (window.location.href.indexOf('env=P')) {      
  env = 'P';
  console.log("P");
} else {
  env = 'A';
  console.log("A");
}   

env is always equal to P no matter what the url is. I am quite sure I have used indexOf before for uri's but am not sure the issue here.

Upvotes: 3

Views: 5022

Answers (3)

jjrdk
jjrdk

Reputation: 1892

That's because indexOf doesn't return 0 and is therefore evaluated as true. Try changing to

if (window.location.href.indexOf('env=P') > -1)

Upvotes: 8

Alex K.
Alex K.

Reputation: 175876

indexOf returns -1 if there is no match, thats a Truthy value, you need to be explicit;

if (window.location.href.indexOf('env=P') === -1) {   
  ///no match   

Upvotes: 0

Quentin
Quentin

Reputation: 943981

indexOf will return -1 if the substring is not in the string, and -1 is a true value.

This is because it returns the index of the substring (so it is 'foo'.indexOf('f') that would return 0).

Your check should be:

if (location.href.indexOf('env=P') >= 0) {

Upvotes: 4

Related Questions