2017-06-24 6 views
1

文字は2つの特定の文字の間に存在する場合のみ置き換えますか?テキストの前後にテキストがあっても?例えば同じ文字の複数の出現箇所を2つの他の文字の間に置き換えます。

、私はこのような文字列を持っている場合:

var text = "For text `in between two backticks, replace all #es with *s`. It should `find all such possible matches for #, including multiple ### together`, but shouldn't affect ### outside backticks." 

私の所望の出力は次のとおりです。

text = text.replace(/`(.*?)#(.*?)`/gm, "`$1*$2`"); 
+0

ので、次の2つの '*'との間に '#'を交換したいですか? –

+0

いいえ、私は2つのバッククォート( ')の間で置き換えたい – KarthaCoder

答えて

2

用途:

"For text `in between two backticks, replace all *es with *s`. It should `find all such possible matches for *, including multiple *** together`, but shouldn't affect ### outside backticks." 

私は、次のコードを持っています単純な/`[^`]+`/g正規表現はバックティックと一致し、1+文字はバックティック以外のものになり、次にバックティCK、およびコールバックの内側#を置き換える:

var text = "For text `in between two backticks, replace all #es with *s`. It should `find all such possible matches for #, including multiple ### together`, but shouldn't affect ### outside backticks."; 
 
var res = text.replace(/`[^`]+`/g, function(m) { 
 
    return m.replace(/#/g, '*'); 
 
}); 
 
console.log(res);

関連する問題