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.
We convert a Number to Boolean by using the JavaScript Boolean() method. A JavaScript boolean results in one of the two values i.e true or false. However, if one wants to convert a variable that stores integer “0” or “1” into Boolean Value i.e “true” or “false”.
JavaScript String indexOf() The indexOf() method returns the position of the first occurrence of a value in a string. The indexOf() method returns -1 if the value is not found. The indexOf() method is case sensitive.
prototype. indexOf() to find out whether the element is present in the array or not. But it doesn't return a boolean. It returns the first index of the element found in the array, or it will return -1 (which represents that the element is not found).
0 and 1 are type 'number' but in a Boolean expression, 0 casts to false and 1 casts to true . Since a Boolean expression can only ever yield a Boolean, any expression that is not expressly true or false is evaluated in terms of truthy and falsy. Zero is the only number that evaluates to falsy.
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
console.log(element.find('div').eq(3).text().indexOf('whatever') > -1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With