[ Web Proxy ]
URL:
Viewing: https://www.javascripttutorial.net/es-next/javascript-string-replaceall/ [Back]  [Original]

JavaScript String replaceAll() Method
Skip to content

String.prototype.replaceAll()

Summary: in this tutorial, you’ll learn about the JavaScript string replaceAll() method that returns a new string with all occurrences of a substring replaced by a new one.

Introduction to the JavaScript string replaceAll() method

The replaceAll() method returns a new string with all occurrences of a substring replaced by a new one.

Here’s the syntax of the replaceAll() method:

replaceAll(pattern, replacement)

In this syntax:

The replacement callback function has the following signature:

replacement(match, offset, str)Code language: JavaScript (javascript)

In this syntax:

Like the replace() method, the replaceAll() method doesn’t change the original string but returns a completely new string with the pattern replaced by the replacement.

Note that the replaceAll() method is available in ES2021 or later.

JavaScript string replaceAll Method [JavaScript string replaceAll Method]

JavaScript String replaceAll() method examples

Let’s take some examples of using the JavaScript String replaceAll() method.

1) Basic JavaScript String replaceAll() example

The following example uses the replaceAll() method to return a new string with the string JS with replaced by the string JavaScript in the string ‘JS will, JS will, JS will rock you':

let str = 'JS will, JS will, JS will rock you.';
let newStr = str.replaceAll('JS', 'JavaScript');

console.log({ newStr });Code language: JavaScript (javascript)

Output:

{
  newStr: 'JavaScript will, JavaScript will, JavaScript will rock you.'
}Code language: JavaScript (javascript)

2) JavaScript String replaceAll() with a callback function example

The following example uses the replaceAll() method to search for a substring by a regular expression and replace each match with a specific replacement determined by a callback function:

let str = 'JS will, Js will, js will rock you.';

let pattern = /js/gi;

const newStr = str.replaceAll(pattern, function (match, offset, str) {
  if (match === 'JS') return 'JavaScript';
  if (match === 'Js') return 'Javascript';
  if (match === 'js') return 'javascript';
  return '';
});

console.log({ newStr });
Code language: JavaScript (javascript)

Output:

JavaScript will, Javascript will, javascript will rock you. 

How it works.

The regular expression /js/gi matches any string that contains the substring JS case-insensitively i.e, JS, Js, or js.

The replaceAll() method replaces the substring JS, Js, and js with the returned value of the replacement callback.

Summary

Was this tutorial helpful ?
Yes No
Search …:

Searching

Trimming

Padding

Extracting

Concatenating

Replacing

Copyright © 2009 - Present by JavaScript Tutorial Website. All Right Reserved.


Web Proxy Viewer  |  New URL  |  Original Page