2

So this seems like a simple question but the following code works but not as I expect This is an example from an online video checking for http in a field. I know there are other questions about the 'correct' way to use indexOf but my question is why this code works.

document.ucDivIntake.website.onchange = function(){
var theURL = document.ucDivIntake.website.value;
    if(theURL.indexOf("http")){
        document.getElementById('errorMessage_website').innerHTML = "need http";
        document.getElementById('errorMessage_website').style('display', 'inline');
    }
}

This does display the error message if http is not present. If http is not found by indexOf it returns -1. I confirm that in my ide debugger. So would that fail the condition and not enter the condition code. Seems like I am missing something basic.

RGB
  • 31
  • 1
  • 6

4 Answers4

2

The .indexOf() function returns a number, not a boolean. The numeric value will be greater than or equal to zero, which means that if "http" appears at the beginning of the search string the result will be 0 and the test will fail.

The clearest thing to do is compare explicitly:

if (theURL.indexOf("http") > -1)
Pointy
  • 405,095
  • 59
  • 585
  • 614
  • 1
    so even if it is getting -1 it is 'true' and meeting the condition, there the condition will be met unless http is at beginning of string? This would explain the result. I thought -1 would be 'false'. – RGB Jan 07 '15 at 21:36
  • @RGB yes exactly. The "falsy" values in JavaScript are `0`, `NaN`, `""`, `null`, `undefined`, and of course `false`. – Pointy Jan 07 '15 at 21:41
1

indexOf returns zero if it's at the beginning of the string. Since zero is "falsy", the if condition is not met.

It should be:

if(theURL.indexOf("http") >= 0)
Joe Enos
  • 39,478
  • 11
  • 80
  • 136
0

in javascript if( [numeric value] ) will always return true if the number is not 0

if 0 it is false.

Buck3y3
  • 136
  • 8
0

indexOf will return where the string is in the target string. If this is at position 0, then this will evaluate as 'falseish' and therefore fail.

Similarly, if it doesn't exist it will return -1 - also falseish.

Fueled By Coffee
  • 2,467
  • 7
  • 29
  • 43