OneCompiler

How to replace all the occurences of a substring in javascript?

I'm trying to replace all the occurences of a substring with another substring, but i'm able to replace only the first occurence using replace function. Any other function or mechanism to replace all the occurences?

1 Answer

6 years ago by

Consider you want to replace hello with happy in the below text, when you do just replace it will only replace the first occurence of hello with happy. If you want to replace all the occurences of hello with happy then you should use a global modifier /g at the end of regular expression to replace all occurences of hello with happy.

text ="hello world hello world hello world";
text = text.replace(/hello/g, 'happy');

verify results here

6 years ago by Divya