5

I was wondering, say I had some thing like the following:

console.log(element.find('div').eq(3).text().indexOf('whatever'));

bearing in mind that element is defined and the console is logging a value of 32 (or anything that isn't -1) what would be the best way of converting the result into a Boolean so my console.log either outputs true or false

Thanks in advance.

2
  • 7
    element.find('div').eq(3).text().indexOf('whatever') > -1 Commented Jan 3, 2014 at 15:01
  • 4
    !!~something.indexOf('whatever')
    – elclanrs
    Commented Jan 3, 2014 at 15:07

2 Answers 2

15

The answer above will work, however if you are as nerdy as I, you will far prefer this:

console.log(~element.find('div').eq(3).text().indexOf('whatever'));

The obscure '~' operator in javascript performs the operation "value * -1 - 1", e.g. ~-2 === 1. The only use case I have ever had for this is in converting the "not found" -1 from ".indexOf()" into "0" (a falsey value in javascript), follow through and see it will convert an index found at position "0" to "-1", a truthy value.

tldr:

~[1,2,3].indexOf(0) // => 0
!!~[1,2,3].indexOf(0) // => false

~[1,2,3].indexOf(1) // => -1
!!~[1,2,3].indexOf(1) // => true
2
  • 1
    You may want to revise your answer, as ~ is not really obscure. It is the bitwise NOT operator, which switches all 1s to 0s in the binary representation of your number. since -1 is 111....1 in binary, it turns to 000....0 which can be cast to false. ... better explanation in this answer: stackoverflow.com/questions/4295578/…
    – Marconius
    Commented Jan 9, 2018 at 14:47
  • 1
    From my tests, both this solution and the accepted solution run at roughly the same time. Ergo, if performance is your concern; it needn't be - choose the solution you prefer for readability. Commented Dec 19, 2018 at 16:11
11
console.log(element.find('div').eq(3).text().indexOf('whatever') > -1);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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