0

请看这个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

“为了”而不是“为了”

4

1 回答 1

2

只是不要替换为短语,而是替换为匹配的字符串:

… target.replace(new RegExp(phrase[indx], "gi"), "~~~$&```");

有了它,您不妨删除循环并仅使用

return target.replace(new RegExp(phrase.join("|"), "gi"), "~~~$&```")
于 2012-08-22T10:06:51.043 回答