What is the correct way to do a regular replacement in JavaScript for all matches found?

Question:

What is the correct way to do a regular replacement in JavaScript for all matches found?

The way I currently do:

var i = 0;
while ((i = str.indexOf("_", i)) != -1) {
    str = str.replace("_", " ");
}

Or until:

str = str.split("_").join(" ");

They do not seem to me to be the most suitable .

Answer:

Use a regular expression in the first argument of replace with the g (global) flag:

str = str.replace(/_/g, ' ');

Read more:

Scroll to Top