Open In App

TypeScript | String replace() Method

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: 



Return Value: This method returns a new changed string. 

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



Example 1: 




<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: 




<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
Article Tags :