A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/javascript-string-replaceall-method/ below:

JavaScript String replaceAll() Method - GeeksforGeeks

JavaScript String replaceAll() Method

Last Updated : 16 Jul, 2024

The replaceAll() method in JavaScript is used to replace all occurrences of a specified substring or pattern with a new substring. The replaceAll() method does not change the original string.

JavaScript's replaceAll() method used for replacing all instances of a specified substring or pattern within a string with a new substring. This method comprehensively updates the string by replacing every occurrence of the target substring or pattern with the provided replacement string.

Note: The original string remains unchanged, preserving its integrity throughout the process.

Syntax:
const newString = originalString.replaceAll(regexp | substr , newSubstr | function)
Parameters:

This method accepts certain parameters defined below: 

Return Value:

Returns a String where the search value has been replaced.

Example 1: String Replace All Occurrences

The function gfg() takes a string "Geeks or Geeks", replaces all occurrences of "or" with "for", and logs the modified string "Geeks for Geeks" to the console.

JavaScript
function gfg() {
    let string = "Geeks or Geeks";
    newString = string.replaceAll("or", "for");
    console.log(newString);
}
gfg();

Example 2: Replace All Occurrences of "coffee" with "tea"

The function GFG() defines a regular expression /coffee/ig to match all occurrences of "coffee" case-insensitively in the string "Lets, have coffee today!". It then replaces all occurrences with "tea" and logs the modified string "Lets, have tea today!" to the console.

JavaScript
function GFG() {
    const regexp = /coffee/ig;
    let string = "Lets, have coffee today!";
    newString = string.replaceAll(regexp, "tea");
    console.log(newString);
}
GFG();

Output
Lets, have tea today!

We have a complete list of Javascript string methods, to check those please go through the Javascript String Complete Reference article.

Supported Browsers:

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4