Open In App

TypeScript String replaceAll method

TypeScript replaceAll method is designed to replace all occurrences of a specified substring within a string with another substring. Unlike the traditional replace method, which only replaces the first occurrence by default, replaceAll replaces all instances of the target substring.

Syntax:

const newString = originalString.replaceAll(searchValue, replaceValue);

Parameters:

Return Value:

The replaceAll method returns a new string with all occurrences of the searchValue replaced with the replaceValue.

Example 1: Implementation to replace every instance of a specific substring in a string.

const originalString: string = 
    "apple, orange, banana, orange";
const newString: string = 
    originalString.replaceAll("orange", "mango");

console.log(newString);

Output:

apple, mango, banana, mango

Example 2: Implementation to show how to use a regular expression with the replaceAll() method.

const originalString: string = 
        "The quick brown fox jumps over the lazy dog";
const newString: string = 
        originalString.replaceAll(/\b\w\b/g, "X");

console.log(newString);

Output:

The quick brown fox jumps over the lazy dog

Example 3: Implementation to show Case-Insensitive Replacement

const originalString = 
    "Hello, world! hello, world!";
const newString = 
    originalString.replaceAll(/hello/gi, "Hi");
console.log(newString); 

Output:

Hi, world! Hi, world!

Browser Support:

Article Tags :