infoMore 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 節を実行する!
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme
What you can do with signing up