replaceAll() replaces every match in a string, and regex gives you a precise way to target patterns instead of fixed text. It is useful when you want to clean whitespace, replace repeated words, or normalize text output.
You can use it with a string pattern or a regular expression pattern. If you are cleaning text before comparison, JavaScript trim and JavaScript toLowerCase are common follow-up steps.
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 every string match
A string pattern replaces every exact match.
let str = "Hello world! Hello world!";
console.log("replaceall-string:", str.replaceAll("world", "JavaScript"));You should see one line logging replaceall-string: Hello JavaScript! Hello JavaScript!.
Use this when the text you want to replace is fixed and exact.
Method 2: Replace every regex match
A global regex lets you replace every match that fits the pattern.
console.log("replaceall-regex:", "a1b2c3".replaceAll(/\d/g, "X"));
console.log("replaceall-word:", "Hello world! Hello world!".replaceAll(/world/g, "JavaScript"));You should see 2 lines, in order: replaceall-regex: aXbXcX, replaceall-word: Hello JavaScript! Hello JavaScript!.
This is the better choice when you need pattern-based replacement instead of exact text replacement.
Method 3: Replace and normalize text
You can combine regex replacement with other string cleanup steps to prepare data for display or comparison.
const input = " Hello world ";
const cleaned = input.replaceAll(/\s+/g, " ").trim();
console.log("replaceall-clean:", cleaned);You should see one line logging replaceall-clean: Hello world.
This is useful when you want a normalized string after replacement.
Summary
JavaScript replaceAll() is a clean way to replace every match in a string. Use a string pattern for exact text and regex for pattern matching, whitespace cleanup, or repeated value replacement.
