LoginSignup
416

More than 5 years have passed since last update.

posted at

updated at

【JavaScript】~を含むかのチェック

matchを使う方法

str.match(/文字列/)で、文字列が含まれれば配列、文字列が含まれなければnullが返ることを利用する。

if ( str.match(/hoge/)) {
//strにhogeを含む場合の処理

}

indexOfを使う方法

str.indexOf(文字列)で、文字列が見つかれば文字列が見つかった場所(0以上)、文字列が見つからなければ-1が返ることを利用する。

返り値!=-1
if ( str.indexOf('hoge') != -1) {
//strにhogeを含む場合の処理

}
ビット反転演算子
if ( ~str.indexOf('hoge')) {
//strにhogeを含む場合の処理

}

ビット反転演算子の解説

文字列が見つからない場合、indexOfが-1を返す。-1をビット反転演算子にかけると、0が返る。if文では、0が真と判定される。

※ビット反転演算子
整数をビット反転演算子にかけると、符号を反転してマイナス1した数になる。
例)
~1 → -2
~-1 → 0
~0 → -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
What you can do with signing up
416