2012-04-06 6 views
2

を交換して使用:クリックで正規表現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でですか?

答えて

4

あなたは右のクラス名の右側の部分を見つけるために正規表現を使うことができhttp://jsfiddle.net/jfriend00/EDrvJ/

正規表現の説明は次のとおりです。

(^|\s) Match starting with either the start of the string^or whitespace \s 
([^\s_]+) After that, match any number of characters that are not whitespace and not underscore and capture this match 
_\d  After that, match an underscore and any digit 
(\s|$) After that, match whitespace or the end of the string 

(^|\s)開始時と(\s|$)終了は、部分一致ではなく、クラス名全体が一致するようにします。 |のシンボルは正規表現でORですので、^または\sのいずれかを(^|\s)と一致させることができます。

+1

'(^ | \ s)'に '|'の必要性は何ですか、Regex – diEcho

+2

私の答えに正規表現全体の説明を追加してください。 '|'は正規表現ORなので '(^ | \ s)'は文字列 '^'の始まりまたは空白 '\ s'のいずれかと一致すると言います。 – jfriend00

+0

@diEcho - 私がやったやり方と同じようにすると、クラス名の部分一致を防ぐことができ、クラス名は任意の順序と任意の数のクラス名にすることができます。 – jfriend00

2

それはjqueryのそれはそれはのようになります。正規表現を使用して

を交換する一般的なJavaScriptの文字列で、置き換えではありません。

var a = $(this).attr('class').replace(/(foo|joe|doe|_1|_2)/g, ''); 

あなたは

のための一般的な何かが必要な場合は、私が欲しいですアンダースコアと数字のクラスの最初の部分を取得します。デモここで働く

$('#foo input').on('click', function() { 
    var match = this.className.match(/(^|\s)([^\s_]+)_\d(\s|$)/); 
    if (match) { 
     var item = match[2]; 
     // do what you want with item here 
    } 
}); 

、直接任意の置換を行わず

var a = $(this).attr('class').match(/\b([^ _]+?)_\d/, ''); 
+1

'のvar A = classes.replace(/.* \? b([az] +)_ \ d。*/'$ 1'); 'もうまくいくでしょう。 – Qtax

1

this testに応じて、split()関数を使用して、「アンダースコアと数字のクラスの最初の部分を取得したい」という文を修正してください。、あなたはあなたが番号なしクラスの最初の部分を必要とアンダー

与えることを強調している何をしていない関数

$('#foo input').on('click', function() { 
    var a = $(this).attr('class').split('_'); 
    console.log(a[0]); 
    }); 
関連する問題