-6

The value of the field with the id 'post_url' is http://www.example.com/. Shouldn't JavaScript return true for anything greater than -1?

alert('1a = '+id_('post_url').value.indexOf('http:'));//      0
alert('1b = '+id_('post_url').value.indexOf('http:') > -1);// false
alert('2a = '+id_('post_url').value.indexOf('www.'));//       7
alert('2b = '+id_('post_url').value.indexOf('www.') > -1);//  false
3
  • 1
    Could you try with an extra set of brackets? alert('1b'+(id_('post_url').value.indexOf('http:')>-1));
    – scragar
    Commented May 27, 2014 at 12:48
  • 4
    Instead of adding the answer to your question, just accept the right answer, please. And for what it's worth, stop messing with the formatting. The bold "Returns" statements are an eyesore, and the extra newlines are not helping anyone determine what's actually returning the values.
    – Cerbrus
    Commented May 27, 2014 at 12:57
  • 1
    As @Cerbrus said, please do not edit in the answer to your question in the question. I'm locking this question to prevent further edits. I think it can just be left as-is. Commented May 27, 2014 at 13:18

4 Answers 4

18

You're comparing a string and a number. You're concatenating the result of indexOf (which I assume is -1) to a string before you do your > comparison. This is equivalent to NaN > -1.

"1b-1" > -1 // => false
0
4

Check Operator Precedence The addition/string concatenation has greater precedence than relational comparison.

Your code needs some brackets/grouping operator to cure that:

alert( '1b = ' + ( id_('post_url').value.indexOf('http:')>-1 ) ); // 1b = true
3

You are attempting to evaluate a string concatenation as a number, which is returning false.

'2b'+id_('post_url').value.indexOf('www.')>-1

...using order of operations, will add the string, 2B to the index returned by, id_('post_url').value.indexOf('www.')

Thus, casting the entire thing as a string, and evaluating whether the string is greater than -1.

Here's how you need to write your alert.

alert(id_('post_url').value.indexOf('www.')>-1);

That should alert 'true'.

1
'2b'+id_('post_url').value.indexOf('www.')

You are adding 2b to index of, so it won't remain an integer but will have value as string of 2b+ whatever index you have. So that is the reason for what you are observing.

Not the answer you're looking for? Browse other questions tagged or ask your own question.