2012-03-29 3 views
1

私は答えが私を見つめていることを賭けているので、私は愚かにこれを尋ねる気がするが、ここに行く。テスト時にregexオブジェクトで作業を置き換えないのはなぜですか?

私はCSSスタイルのtextDecorationから文字列を取り込み、その文字列の下線部分(およびその周りの空白部分)を削除しようとしています。私はtest()を実行するとtrueを返しますが、replaceメソッドを実行すると文字列は変更されません。助けて?

マイコード:

textDecoration = function(str) { 
      var n_str = str + '|/\s' + str + '|/\s' + str + '/\s|' + str + '/\s'; 
      var nre = new RegExp(n_str, "g"); 
      debug_log('Found or not: ' + nre.test(txt)); 
      txt.replace(nre, ''); 
      debug_log('Result: ' + txt); 
      debug_log('-----------------------'); 
    } 

    var txt = "underline"; 
    debug_log('-----------------------'); 
    debug_log('Starting String: ' + txt); 
    textDecoration("underline"); 
    txt = "underline overline line-through"; 
    debug_log('-----------------------'); 
    debug_log('Starting String: ' + txt); 
    textDecoration("underline"); 
    txt = "overline underline line-through"; 
    debug_log('-----------------------'); 
    debug_log('Starting String: ' + txt); 
    textDecoration("underline"); 
    txt = "overline line-through underline"; 
    debug_log('-----------------------'); 
    debug_log('Starting String: ' + txt); 
    textDecoration("underline"); 

出力:

The output

答えて

4

replace()は置き換えと新しい文字列を返し、実際の文字列を変更しないでください。

var newString = txt.replace(nre, ''); 
debug_log('Result: ' + newString); 
+0

私は恥ずかしいです...ありがとう。私はT-Minusで8分間受け入れます。 –

1

testはブール値を返します。 replaceは新しい文字列を返します。文字列は変更されません。

また、あなたの正規表現はかなり奇妙です。 str = "underline"を適用すると、あなたが取得します:空白と一致しますが、"/s"しない

/underline|\/sunderline|\/sunderline\/s|underline\/s/ 

+0

正規表現は初めてです。私はそれが "下線"、 "下線"、 "下線"、 "下線"と一致すると仮定していました。私が間違っている? –

+0

あなたの文字列では、RegExpコンストラクタを指定しました.sは(sに)エスケープされ、sはスラッシュを表します。正規表現のための空白メタ文字にするには、文字列中の文字の前にバックスラッシュをエスケープする必要があります。また、「アンダーライン」の両側の空白を削除しないでください:-) – Bergi

+0

ああ、両方の空白を削除しないでよかった!それが中間のものなら、私は問題を抱えています。私はいくつかのより多くの検索を行い、それらを適切にエスケープする方法を理解します。助けてくれてありがとう! –

関連する問題