JavaScript String replace()

The JavaScript replace() method returns a new string with the specified string/regex replaced.

The syntax of replace() is:

str.replace(pattern, replacement)

Here, str is a string.


replace() Parameter

The replace() method takes in:

  • pattern - either a string or a regex that is to be replaced
  • replacement - the pattern is replaced with this replacement (can be either a string or a function)

Return Value from replace()

  • The replace() method returns a new string with the specified pattern replaced.

Example 1: Replace the first occurrence

const text = "Java is awesome. Java is fun."

// passing a string as the first parameter
let pattern = "Java";
let new_text = text.replace(pattern, "JavaScript");
console.log(new_text);

// passing a regex as the first parameter
pattern = /Java/;
new_text = text.replace(pattern, "JavaScript");
console.log(new_text);

Output

JavaScript is awesome. Java is fun.
JavaScript is awesome. Java is fun.

In both replace() methods, the first occurrence of Java is replaced with JavaScript.


Example 2: Replace all occurrences

To replace all occurrences of the pattern, you need to use a regex with a g switch (global search). For example, /Java/g instead of /Java/.

const text = "Java is awesome. Java is fun."

// notice the g switch in the regex pattern
const pattern = /Java/g;

const new_text = text.replace(pattern, "JavaScript");
console.log(new_text);

Output

JavaScript is awesome. JavaScript is fun.

Here, the replace() method replaces both occurrences of Java with JavaScript.


Replace Without Considering Uppercase/Lowercase

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

Example 3: Case-Insensitive Replacement

const text = "javaSCRIPT JavaScript"

// the first occurrence of javascript is replaced
let pattern = /javascript/i;  // case-insensitive search
let new_text = text.replace(pattern, "JS");
console.log(new_text)  // JS JavaScript

// all occurrences of javascript is replaced
pattern = /javascript/gi;  // case-insensitive and global search
new_text = text.replace(pattern, "JS");
console.log(new_text)  // JS JS

Output

JS JavaScript
JS JS

Example 4: Passing Function as a Replacement

You can also pass a function (instead of a string) as the second parameter to the replace() method.

const text = "Random digit: 3"

// generate a random digit between 0 and 9
function generateRandomDigit() {
  return Math.floor(Math.random() * 10)
}

// regex to match a digit
const pattern = /\d/;

const new_text = text.replace(pattern, generateRandomDigit);
console.log(new_text)

Output

Random digit: 8

You may get different output when you run this program. It's because the first digit in text is replaced with a random digit between 0 and 9.


Recommended Reading: JavaScript String replaceAll()