请查看JsFiddle。
var target = "Thanks For Looking This Problem";
var phrase = ["anks", "for", "king T"];
for(var indx = 0; indx < phrase.length; indx ++)
{
target = target.replace(new RegExp(phrase[indx], "gi"), "~~~" + phrase[indx]+ "```");
}
我得到了这个输出:Th~~~anks``` ~~~for``` Loo~~~king T```his Problem
但我需要这个输出:Th~~~anks``` ~~~For``` Loo~~~king T```his Problem
'For'代替'for'
答案 0 :(得分:2)
请不要使用短语replace,而是使用匹配的字符串:
… target.replace(new RegExp(phrase[indx], "gi"), "~~~$&```");
有了这个,您也可以删除循环并仅使用
return target.replace(new RegExp(phrase.join("|"), "gi"), "~~~$&```")