VOOZH about

URL: https://www.geeksforgeeks.org/typescript/typescript-string-replace-method/

⇱ TypeScript String replace() Method - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

TypeScript String replace() Method

Last Updated : 19 Jul, 2024

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.

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.

Output:

TypeScript JavaScript JavaScript
Comment
Article Tags:
Article Tags:

Explore