Explain Codes LogoExplain Codes Logo

How do I replace all occurrences of a string in JavaScript?

javascript
regex
string-replacement
best-practices
Nikita BarsukovbyNikita Barsukov·Aug 11, 2024
TLDR

To replace all incidences of a string in JavaScript, lean on the .replace(/pattern/g, 'replacement') pattern:

let text = "How much wood could a woodchuck chuck?"; let result = text.replace(/wood/g, "noodles"); console.log(result); // "How much noodles could a noodleschuck chuck?"

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:

let variable = "a woodchuck"; let regex = new RegExp(variable, "g"); // The "g" indicates global replacement let result = text.replace(regex, "spaghetti monster"); // Et voila!

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:

function escapeRegExp(string) { return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); } let trickyVariable = "sneaky*escape" let escapedVariable = escapeRegExp(trickyVariable); let regex = new RegExp(escapedVariable, "g"); let result = text.replace(regex, "we outsmarted you, asterisk!");

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:

if (!String.prototype.replaceAll) { String.prototype.replaceAll = function (search, replacement) { return this.split(search).join(replacement); }; }

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:

while (text.includes("wood")) { text = text.replace("wood", "noodles"); }

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:

let searchParty = userInput; // even when it has special characters lurking let safeParty = escapeRegExp(searchParty); let regex = new RegExp(safeParty, "g"); let partyResult = text.replace(regex, "Crash this!");

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:

let result = text.replace('wood', 'noodles'); // Only the first "wood" gets the noodle treatment

Like the saying goes, there can only be one...noodle? At least in this string.