- ES6 Tutorial
- ES6 - Home
- ES6 - Overview
- ES6 - Environment
- ES6 - Syntax
- ES6 - Variables
- ES6 - Operators
- ES6 - Decision Making
- ES6 - Loops
- ES6 - Functions
- ES6 - Events
- ES6 - Cookies
- ES6 - Page Redirect
- ES6 - Dialog Boxes
- ES6 - Void Keyword
- ES6 - Page Printing
- ES6 - Objects
- ES6 - Number
- ES6 - Boolean
- ES6 - Strings
- ES6 - Symbol
- ES6 - New String Methods
- ES6 - Arrays
- ES6 - Date
- ES6 - Math
- ES6 - RegExp
- ES6 - HTML DOM
- ES6 - Iterator
- ES6 - Collections
- ES6 - Classes
- ES6 - Maps And Sets
- ES6 - Promises
- ES6 - Modules
- ES6 - Error Handling
- ES6 - Object Extensions
- ES6 - Reflect API
- ES6 - Proxy API
- ES6 - Validations
- ES6 - Animation
- ES6 - Multimedia
- ES6 - Debugging
- ES6 - Image Map
- ES6 - Browsers
- ES7 - New Features
- ES8 - New Features
- ES9 - New Features
- ES6 Useful Resources
- ES6 - Quick Guide
- ES6 - Useful Resources
- ES6 - Discussion
ES6 - replace()
This method finds a match between a regular expression and a string, and replaces the matched substring with a new substring.
The replacement string can include the following special replacement patterns −
Sr.No | Patterns & Inserts |
---|---|
1 |
$$ Inserts a "$". |
2 |
$& Inserts the matched substring. |
3 |
$` Inserts the portion of the string that precedes the matched substring. |
4 |
$' Inserts the portion of the string that follows the matched substring. |
5 |
$n or $nn Where n or nn are decimal digits, inserts the nth parenthesized submatch string, provided the first argument was a RegExp object. |
Syntax
string.replace(regexp/substr, newSubStr/function[, flags]);
Argument Details
regexp − A RegExp object. The match is replaced by the return value of parameter #2.
substr − A String that is to be replaced by newSubStr.
newSubStr − The String that replaces the substring received from parameter #1.
function − A function to be invoked to create the new substring.
flags − A String containing any combination of the RegExp flags: g.
Return Value
It simply returns a new changed string.
Example
var re = /apples/gi; var str = "Apples are round, and apples are juicy."; var newstr = str.replace(re, "oranges"); console.log(newstr)
Output
oranges are round, and oranges are juicy.
Example
var re = /(\w+)\s(\w+)/; var str = "zara ali"; var newstr = str.replace(re, "$2, $1"); console.log(newstr);
Output
ali, zara
To Continue Learning Please Login
Login with Google