When checking for existence of a substring I have been doing this:
var that = "ok hello cool";
if( that.indexOf('hello') + 1 ) {
}
Instead of:
if( that.indexOf('hello') != -1 ) {
}
Am I overlooking something or is there a reason not to do this.
Update:
Yes, I was indeed unaware of the even simpler method of:
if ( ~that.indexOf( 'hello' ) ) {
}
You can read about the ~
bitwise operator and the other queer bitwise operators here:
https://developer.mozilla.org/en/JavaScript/Reference/Operators/Bitwise_Operators
if( ~that.indexOf('hello') )
is usually used \$\endgroup\$indexOf(...) >= 0
? \$\endgroup\$~
is a lot cleaner than>= 0
. \$\endgroup\$