Sathya
Sathya

Reputation: 5308

JavaScript regular expression case insensitivity

Please look this 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]+ "```");
}
​

I get this output: Th~~~anks``` ~~~for``` Loo~~~king T```his Problem

But I need this output: Th~~~anks``` ~~~For``` Loo~~~king T```his Problem

'For' instead of 'for'

Upvotes: 0

Views: 84

Answers (1)

Bergi
Bergi

Reputation: 664246

Just don't replace by the phrase, but by the matched string:

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

With that, you might as well remove the loop and use only

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

Upvotes: 2

Related Questions