Ram Singh Ram Singh - 5 months ago 16
JSON Question

How to replace all existence of chars from string in jquery?

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.

Answer

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