Open In App

TypeScript String replaceAll method

Last Updated : 03 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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);
  • originalString: The original string in which replacements are to be made.
  • searchValue: The substring to be replaced.
  • replaceValue: The substring to replace all occurrences of searchValue.

Parameters:

  • searchValue: The substring to find and replace. This can be a string or a regular expression.
  • replaceValue: The string that replaces the searchValue.

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.

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

JavaScript
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

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

Output:

Hi, world! Hi, world!

Browser Support:

  • Chrome: 85+
  • Edge: 85+
  • Firefox: 77+
  • Safari: 13.1+
  • Opera: 71+

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads