LoginSignup
6
6

More than 5 years have passed since last update.

文字列にキーワードが含まれるか判定する略記法

Last updated at Posted at 2012-03-16
if (~string.indexOf(keyword)) {
  // found
} else {
  // not found
}
  • String.indexOf() は引数のキーワードが見つからなかったとき -1 を返す
  • Bitwise NOT演算子 ~ はオペランドを符号付き32ビット整数とみなしてビットを反転させる
  • ~(-1) === 0 であり、Bitwise NOTが 0 になるのはこれのみ
  • したがって上記のコードは indexOf() が -1 のとき = キーワードが見つからなかったときのみ else 節を実行する!
6
6
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6