Replace all occurences if a substring in a string

Published on 2024-11-23 by Raul

Using javascript's replace method will only replace the first occurence of a substring in a string. To replace all occurences, you'll need to use a regular expression:

str = haystack.replace(/needle/g, 'replacement');

 Notice that you don't need quotes for the needle, since it's a regular expression.


Keep in touch


About

Hey there, I'm Raul, owner of CreativeCLR, a small consulting company.

Feel free to drop me any question you might have on this post using the comment section or the contact page.