LoginSignup
5
2

More than 5 years have passed since last update.

hasClass で regex(正規表現)を使おうとしました

Posted at

jQuery の hasClass で正規表現を使おうと思ったのですが、使えなかったので、それを実現します。

問題

先頭が hoge のクラスを持つかどうかを判断したいです。

<div id="sample1" class="non-hoge piyo">
  I do not seek, I find.
</div>

<div id="sample2" class="foo hoge99">
  Live the life you love.
</div>

例えば、上のようなとき。

$('#sample1') => false
$('#sample2') => true

となるような判別をしたいです。

方法

hasClass だと足りない

$('#sample1').hasClass('hoge');
// => false
$('#sample2').hasClass('hoge');
// => false

is('[class=hoge]') でも足りない

// 行頭一致
$('#sample1').is('[class^=hoge]');
$('#sample2').is('[class^=hoge]');
// => 両方:false

// 区切って一致
$('#sample1').is('[class~=hoge]');
$('#sample2').is('[class~=hoge]');
// => 両方:false

// 部分一致
$('#sample1').is('[class*=hoge]');
$('#sample2').is('[class*=hoge]');
// => 両方:treu

なので test で愚直にやってみます..

/(^|\s)hoge\S*/g.test($('#sample1').prop('class'));
// => false

/(^|\s)hoge\S*/g.test($('#sample2').prop('class'));
// => true

できました。

おわりに

スクリーンショット 2016-10-20 15.50.58.png

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