JavaScript Symbol replace the property is used to determine the method that replaces the matched substring of a string. This function is called by the String replace() method.
Syntax:
[Symbol.replace](string)
Parameters: It accepts single parameter “String”.
Return value: It will return a new string. The below examples illustrate the Symbol.replace the property in JavaScript:
Below examples illustrate the JavaScript Symbol replace Property
Example 1: In this example, we will
javascript
class Replace1 { constructor(value) { this .value = value; } [Symbol.replace](string) { return `${string} --> ${ this .value}`; } } console.log( 'neveropen' .replace( new Replace1( 'GEEKSFORGEEKS' ))); console.log( 'Article written by ' .replace( new Replace1( 'Shubham Singh' ))); |
Output:
"neveropen --> GEEKSFORGEEKS" "Article written by --> Shubham Singh"
Example 2:
javascript
class Replace2 { constructor(value) { this .value = value; } [Symbol.replace](string) { return `${string}`; } } let val = new Replace2( "neveropen" ); console.log( "Before: " + val.value); console.log( "After: " + val.value .toUpperCase().replace(val.value)); let val2 = new Replace2( "Few Users" ); console.log( "Before: " + val2.value); console.log( "After: " + "Millions of Users" .replace(val2.value)); |
Output:
"Before: neveropen" "After: GEEKSFORGEEKS" "Before: Few Users" "After: Millions of Users"
Supported Browsers: The browsers supported by Symbol replace property are listed below:
- Google Chrome 51
- Firefox 50
- Edge 15
- Opera
- Apple Safari
We have a complete list of Javascript symbols’ properties and methods, to check those please go through the Javascript Symbol Complete Reference article.