Open In App

TypeScript | String replace() Method

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

The replace() is an inbuilt function in TypeScript which is used to find a match between a regular expression and a string, and replaces the matched substring with a new substring. 
Syntax:

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

Parameter: This method accept five parameter 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: 

JavaScript




<script>
    // Original strings
    var str = "Geeksforgeeks - Good Platform"
  
    var re = /Good/gi; 
  
    // Use of String replace() Method
    var newstr = str.replace(re, "Best"); 
    console.log(newstr);
</script>


Output: 

Geeksforgeeks - Best Platform

Example 2: 

JavaScript




<script>
    // Original strings
    var str = "Geeksforgeeks TypeScript"
  
    var re = /(\w+)\s(\w+)/; 
  
    // use of String replace() Method
    var newstr = str.replace(re, "$2 $1"); 
    console.log(newstr);
</script>


Output: 

TypeScript Geeksforgeeks

Last Updated : 18 Jun, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads