5
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

js で完全一致をまとめてやりたい時

Last updated at Posted at 2019-04-01

文字列の完全一致判定

言わずもがな === を使います。

if (redFruit === 'apple') {
  console.log('リンゴです。');
}

文字列の部分一致判定

test が使えますね。

if (/appl/.test(redFruit)) {
  console.log('たぶんリンゴです。');
}

文字列の完全一致をまとめて判定

こういう長い条件が...

// isMyTaste: 好みかどうか
if (redFruit === 'apple' || redFruit === 'strawberry' || redFruit === 'rasberry' || isMyTaste) {
  console.log('個人的に美味しいと思う果物です。');
}

test の正規表現で OR を使うとまとめて判定できます。

// isMyTaste: 好みかどうか
if (/^(apple|strawberry|rasberry)$/.test(redFruit) || isMyTaste) {
  console.log('個人的に美味しいと思う果物です。');
}

補足

^ ... 文字列の先頭を表す
$ ... 文字列の末尾を表す
| ... OR
なので、^$ で判定したい文字列(パターン) をくくってあげて、| で完全一致判定をまとめて実行することができます。

5
7
4

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
5
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?