Replace all occurrences of a string

The replace() method in JavaScript searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced. But, if a string contain repeated words, replace() method change the first occurrence of the string only. example
str = "one two three one five nine"; newStr = str.replace('one', 'XXX'); alert(newStr);

When you run the code, above script will return "XXX two three one five nine". Here you can see, first 'one' is replaceed by 'XXX' and second 'one' still there. So, how you can change the all occurrences of a string in JavaScript?

Replace all occurrence using Split() and join()

You can replace all occurances of a string using Split() and join() function. The string you entered split() with specified word and again join with replaced word. example
str = "one two three one five nine"; newStr = str.split("one").join("XXX");; alert(newStr);
output
XXX two three XXX five nine

Replace all occurrence using RegularExpression

example
str = "one two three one five nine"; newStr = replaceAll(str,'one','XXX'); alert(newStr); function replaceAll(str, find, replace) { return str.replace(new RegExp(find, 'g'), replace); }