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.
let myString = "Hello, world!";
myString = myString.replaceAll("world", "JavaScript");
console.log("replaceall:", myString);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.
const input = "This is a test string.";
console.log("replaceall:", input.replaceAll(/\s/g, ""));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.
const dashed = "a-b-c-d-e";
console.log("replaceall-dashes:", dashed.replaceAll(/-/g, "_"));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.
