javascript : how to replace all the occurrences of a string in another string

Did you know? javascript replace methods replaces first occurrence of the string only. For example if I have a string in javascript such as topics, initiatives, communities and if I want to remove “,” from the string and I use replace method such as :

var str = ‘topics, initiatives, communities’;

var new_str = str.replace(‘,’,”);


Now, it will replace the first comma only, so I will have this in new_str :

topics initiatives, communities

Here keep in mind, that javascript replace method returns new string. It doesn’t replace the original string.

If you want to replace the original string then assign the return string by replace method to original string, such as :

var str =┬ástr.replace(‘,’,”);

This will change the original string.

So, to replace all the commas globally from the string, I will have to use global arguments in the replace function such as :

var new_str = str.replace(/,/g, ”);

And it will return me my desired string i.e. topics initiatives communities

So, never forget to use /g arguments in replace method if you want to replace all the occurrences of the string.

Leave a Reply