JavaScript正则表达式不区分大小写

时间:2012-08-22 10:03:27

标签: javascript regex

请查看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'

1 个答案:

答案 0 :(得分:2)

请不要使用短语replace,而是使用匹配的字符串:

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

有了这个,您也可以删除循环并仅使用

return target.replace(new RegExp(phrase.join("|"), "gi"), "~~~$&```")