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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output: 

Geeksforgeeks - Best Platform

Example 2: 

JavaScript

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output: 

TypeScript Geeksforgeeks

full-stack-img

My Personal Notes arrow_drop_up

Small things always make you to think big

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.