JavaScript String replace()

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

Example


replace() Syntax

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)

relace() Return Value

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

Example 1: Replace the first occurrence

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/.

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 an i switch (case-insensitive search).

Example 3: Case-Insensitive Replacement

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.

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()