At work we're using a custom JavaScript engine that has regular expressions disabled for performance reasons.
I've gotten stuck with this problem for the last couple of hours. I simplified it for this post. Let's say I have this string:
var str = "nice weather, nice car, nice clothes, nice tv";
I want to replace all occurrences of "nice" with "ugly".
JavaScript's replace()
function does just that - it replaces "nice" with "ugly" but here's the problem - if I do str.replace("nice", "ugly")
then JavaScript will replace only first occurance of "nice" with "ugly".
I know that the solution to replace all occurrences is to use a regular expression such as /nice/g
to match globally and run it as str.replace(/nice/g, "ugly")
but in my case, I can't use a regular expression (because as I mentioned we use a custom JavaScript engine with regular expression engine disabled.)
Bottom line is:
I can't figure out how to replace a string with just replace()
function. How can I do it?