0

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'

0

1 Answer 1

2

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"), "~~~$&```")
Sign up to request clarification or add additional context in comments.

2 Comments

thanks. any good tutorial to learn regular expression. because i couldn't find your method in google search.
The linked docs explains about the replace syntax. To learn using Regexes in JS, you might read MDN's guide, to learn regular expression syntax (and lot more) go with regular-expressions.info

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.