LoginSignup
0
1

More than 5 years have passed since last update.

自分メモ:文字列の中に「?」があるかどうか判定

Posted at

ついでに「?」が何個あるかも出す。

sample.js
$(function(){
  if('http://google.com'.match(/[¥?]/g)){
    console.log('http://google.com'.match(/[¥?]/g).length);
  }else{
    console.log(0);
  };
});

matchで対象文字列に検索対象があるかどうかを判定。
あれば配列として、なければnullが返される。
で、nullならば0を返すようにしたものが上記。

さすがに冗長なコードなのでそれっぽくまとめると

refactoring.js
$(function(){
  var hits = 'http://google.com'.match(/[¥?]/g);
  var result = hits ? hits.length : 0;
  console.log(result);
});

こんな感じで着地(謎)

0
1
2

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
0
1