It’s awkward to find out that the the string.replace(targetString, replaceWith) function in JavaScript doesn’t act like it does in most other modern programming languages.

JavaScript will only find the first instance of the target string and replace it. It will not continue to find other instances of the targeted string and replace it.

Java/.Net/etc. will search for all occurrences of the target string and replace it with the replace string.

So, here’s the quick and easy way to change your single replacement to an all replacement. Note that the ‘g’ in the regexp below is important as it specifies the expression to search globally.

str.replace(new RegExp('targetedString', 'g'), 'replaceWith');

Another crafty way to do this is to use the split and join functions in JavaScript that will… split and re-join the string.

str.split('targetedString').join('replaceWith');

Photo by Steve Johnson on Unsplash