LoginSignup
498
416

More than 5 years have passed since last update.

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

Last updated at Posted at 2014-05-19

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

498
416
7

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
498
416