JavaScript replaceAll() for String Replacement

Learn JavaScript replaceAll() with string and regex examples, plus how to replace every matching value in a string.

Published

Updated

Read time 2 min read

Reviewed byDeepak Prasad

JavaScript replaceAll() for String Replacement

replaceAll() is the JavaScript string method you use when you want every match in a string replaced, not just the first one. It is useful for cleanup, formatting, and text normalization.

This method works with string patterns and regular expressions. When you later need to reduce text to a simpler form, JavaScript trim and JavaScript toLowerCase often fit the same workflow.

Tested on: Node.js v20.18.2. A short note after each runnable snippet describes what you should see in the console.


Method 1: Replace text with a string pattern

A string pattern replaces every matching occurrence.

javascript
let myString = "Hello, world!";
myString = myString.replaceAll("world", "JavaScript");
console.log("replaceall:", myString);
Output

You should see one line logging replaceall: Hello, JavaScript!.

Use this when the replacement target is plain text and you want every match updated.


Method 2: Replace all whitespace with a regex

A global regex is required: String.prototype.replaceAll with a RegExp throws if the pattern is not global (g). Use /pattern/g.

javascript
const input = "This is a test string.";
console.log("replaceall:", input.replaceAll(/\s/g, ""));
Output

You should see one line logging replaceall: Thisisateststring..

This is a common pattern for compacting text before validation or comparison.


Method 3: Replace every regex match (not just the first)

replace() only changes the first match unless you use a global regex; replaceAll() with a string replaces every literal occurrence, and with a regex replaces every match when the regex is global.

javascript
const dashed = "a-b-c-d-e";
console.log("replaceall-dashes:", dashed.replaceAll(/-/g, "_"));
Output

You should see one line logging replaceall-dashes: a_b_c_d_e.

Use this when you need repeated pattern-based replacements in one call.


Summary

JavaScript replaceAll() is the right method when every match in a string must be replaced. Use it with plain strings for simple substitutions. With a RegExp, the pattern must include the g flag; otherwise JavaScript throws TypeError.


Official documentation

Olorunfemi Akinlua

Boasting over five years of experience in JavaScript, specializing in technical content writing and UX design. With a keen focus on programming languages, he crafts compelling content and designs …