を交換して使用:クリックで正規表現VS jQueryのは、このHTMLを考える
<div id="foo">
<input type=button class="foo abtn_1">
<input type=button class="joe bbtn_2">
<input type=button class="doe cbtn_2">
<input type=button class="joe dbtn_1">
<input type=button class="foo ebtn_2">
</div>
、私は、アンダースコアと番号を持つクラスの最初の部分を取得したいです。
だから私は取得されるだろう最初の入力から:
は、現在私が使用abtn:
$('#foo input').on('click', function() {
var a = $(this).attr('class')
.replace('foo','')
.replace('joe','')
.replace('doe','')
.replace('_1','')
.replace('_2','')
console.log(a);
});
私はやってのより堅牢で高速なパフォーマンス - 賢明な方法があるはず想像しますこれはおそらくRegexでですか?
'(^ | \ s)'に '|'の必要性は何ですか、Regex – diEcho
私の答えに正規表現全体の説明を追加してください。 '|'は正規表現ORなので '(^ | \ s)'は文字列 '^'の始まりまたは空白 '\ s'のいずれかと一致すると言います。 – jfriend00
@diEcho - 私がやったやり方と同じようにすると、クラス名の部分一致を防ぐことができ、クラス名は任意の順序と任意の数のクラス名にすることができます。 – jfriend00