请看这个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```他的问题
但是我需要这个输出:Th~~~anks``` ~~~For``` Loo~~~king T```他的问题
“对于”而不是“对于”
最佳答案
只是不要replace通过短语,但通过匹配的字符串:
… target.replace(new RegExp(phrase[indx], "gi"), "~~~$&```");
有了这个,您不妨删除循环并仅使用
return target.replace(new RegExp(phrase.join("|"), "gi"), "~~~$&```")
关于JavaScript 正则表达式不区分大小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12070743/