-1

I want to replace all existence of chars from a string, but it is not working. here is my code:

 $.each(jsonArray, function (fromString, jtm) {
   // tempString = tempString.replace(jtm.from, jtm.to)
   tempString = tempString.replaceAll(jtm.from, jtm.to);
 });

I checked to use global to replace all as Told in this article but i am not getting how i can implement in my code.

Please help me.

Community
  • 1
  • 1
Ram Singh
  • 6,664
  • 35
  • 100
  • 166

1 Answers1

3

In javascript there is no method like replaceAll(), to remove all occurrence you need to use regex with global flag.

tempString = tempString.replace(new RegExp(jtm.from,'g'), jtm.to);


In case string contains characters which have special meaning in regex then escape them first.
tempString = tempString.replace(new RegExp(jtm.from.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&'),'g'), jtm.to)

Refer : Converting user input string to regular expression

Community
  • 1
  • 1
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188