Friday, September 5, 2025
HomeLanguagesJavascriptTypeScript | String replace() Method

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: 

  • 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 = "Geeksforneveropen - Good Platform"
  
    var re = /Good/gi; 
  
    // Use of String replace() Method
    var newstr = str.replace(re, "Best"); 
    console.log(newstr);
</script>


Output: 

Geeksforneveropen - Best Platform

Example 2: 

JavaScript




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


Output: 

TypeScript Geeksforneveropen
RELATED ARTICLES

Most Popular

Dominic
32269 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6638 POSTS0 COMMENTS
Nicole Veronica
11802 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11866 POSTS0 COMMENTS
Shaida Kate Naidoo
6752 POSTS0 COMMENTS
Ted Musemwa
7027 POSTS0 COMMENTS
Thapelo Manthata
6704 POSTS0 COMMENTS
Umr Jansen
6721 POSTS0 COMMENTS