replaceAll() with Regex in JavaScript

Deepak Prasad
Short on time?Beta Get the gist of this 2-minute read in seconds, then ask follow-up questions

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.

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

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.

javascript
console.log("replaceall-regex:", "a1b2c3".replaceAll(/\d/g, "X"));
console.log("replaceall-word:", "Hello world! Hello world!".replaceAll(/world/g, "JavaScript"));
Output

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.

javascript
const input = "  Hello   world  ";
const cleaned = input.replaceAll(/\s+/g, " ").trim();
console.log("replaceall-clean:", cleaned);
Output

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.


Official documentation

Finished reading?Beta Get the key takeaways in seconds, then ask follow-up questions
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 user-friendly interfaces to enhance digital experiences across various domains.

  • JavaScript
  • Web Design