Skip to content

JavaScript replaceAll() | String method

  • by

Use the JavaScript replaceAll() method to replace all matches of a pattern in a given string. This method returns a new string with all matches of a pattern replaced by a replacement.

str.replaceAll(pattern, replacement)

The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match.

JavaScript replaceAll() example

Simple example code.

<!DOCTYPE html>
<html lang="en">

    const text = "Java is easy to code. Java is fun.";

    let res = text.replaceAll("Java", "JavaScript");

    new_text = text.replaceAll(/Java/g, "JavaScript");



JavaScript replaceAll String method

Case-Insensitive Replacement

To perform the case-insensitive replacement, you need to use a regex with a i switch (case-insensitive search).

const text = "javaSCRIPT JavaScript";

let pattern = /javascript/gi; // case-insensitive and global search
let new_text = text.replaceAll(pattern, "JS");

console.log(new_text); // JS JS

JavaScript String replace vs replaceAll

One difference with replaceAll is that when passing it a string, it will automatically do a global replacement. This is where you might save yourself a bit of typing, by not having to enter a global flag.

Do comment if you have any doubts or suggestions on this JS method topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading