How do I replace all occurrences of a string in JavaScript?
To replace all incidences of a string in JavaScript, lean on the .replace(/pattern/g, 'replacement')
pattern:
Covering your bases: Regex for universal support
For cross-environment usage, regex proves more universal. If you're dealing with variable substrings, create a RegExp
object:
In woodchucks we trust, all others pay cash... in spaghetti?
Dodging the special character bullet
Special characters in your patterns can cause quite a mess. Using regex? Then don't forget escaping to avoid funky results:
Dear asterisk, we see you trying to sneak into our regex... not on our watch!
When all else fails: the split-and-join strategy
When String.replaceAll()
isn't an option, the split n
join method swoops in to save the day. We mean this literally, by the way:
A good temporary superhero move; for maintainability, avoid altering native prototypes.
Going commando – replace without regex
Singling out situations where regex seems like overkill, going old school with a good, solid loop is a less glamorous, but viable approach:
This loop walks the noodle around the block, replacing all wood on its path.
Handling special cases
Stuck with dynamic patterns? Veer towards the escapeRegExp
escape route for safe and care-free replacements:
Even party crashers have a purpose. They help make our replace function more robust.
One-off replacement
When only wanting a single instance replacement, wave goodbye to the g
flag:
Like the saying goes, there can only be one...noodle? At least in this string.
Was this article helpful?