Open In App

TypeScript String replace() Method

Last Updated : 19 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The replace() method in TypeScript is used to find matches between a regular expression or a substring and a string, replacing the matched substring with a new substring or the value returned by a function.

Syntax

string.replace(regexp/substr, newSubStr/function[, flags]);

Parameter: This method accepts five parameters as mentioned above and described below: 

  • regexp: This parameter is a RegExp object.
  • substr: This parameter is a String that is to be replaced.
  • newSubStr: This parameter is a String that replaces the substring.
  • function: This parameter is a function to be invoked to create the new substring.
  • flags: This parameter is a String containing any combination of the RegExp flags.

Return Value: This method returns a new changed string. 

Below example illustrate the  String replace() method in TypeScriptJS:

Example 1: Basic Usage

This example demonstrates how to replace a simple substring with another string.

JavaScript
const str: string = "Geeksforgeeks is a great platform.";
const newStr: string = str.replace("great", "best");
console.log(newStr);

Output: 

Geeksforgeeks is a best platform.

Example 2: Using a Regular Expression

This example shows how to replace all occurrences of a substring using a regular expression.

JavaScript
const str: string = "TypeScript Geeksforgeeks Geeksforgeeks";
const newStr: string = str.replace(/Geeksforgeeks/g, "JavaScript");
console.log(newStr);

Output: 

TypeScript JavaScript JavaScript

Next Article

Similar Reads