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>
var str = "Geeksforgeeks - Good Platform" ;
var re = /Good/gi;
var newstr = str.replace(re, "Best" );
console.log(newstr);
</script>
|
Output:
Geeksforgeeks - Best Platform
Example 2:
JavaScript
<script>
var str = "Geeksforgeeks TypeScript" ;
var re = /(\w+)\s(\w+)/;
var newstr = str.replace(re, "$2 $1" );
console.log(newstr);
</script>
|
Output:
TypeScript Geeksforgeeks
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
18 Jun, 2020
Like Article
Save Article