replaceAll() with Regex in JavaScript

Tech reviewed: Deepak Prasad
replaceAll() with Regex in JavaScript

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: The examples were tested with Node.js v20.18.1 on a Linux system. The same replaceAll behavior works in modern browsers and JavaScript runtimes.


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"));

Tested output:

text
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"));

Tested output:

text
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);

Tested output:

text
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

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 …

  • JavaScript
  • Web Design