JavaScript | Symbol.replace Property

The Symbol.replace property in JavaScript is well-known symbol that is used to determine the method that replace the matched substring of a string. This function is called by the String.prototype.replace() method.

Syntax:

[Symbol.replace](string) 

Parameters: It accepts single parameter “String”.

Return value: It will return a new string.

Below examples illustrate the Symbol.replace property in JavaScript:



Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

class Replace1 {
    constructor(value) {
        this.value = value;
    }
      
    [Symbol.replace](string) {
        return `${string} --> ${this.value}`;
    }
}
  
console.log('geeksforgeeks'.replace(
            new Replace1('GEEKSFORGEEKS')));
              
console.log('Article written by '.replace(
            new Replace1('Shubham Singh')));

chevron_right


Output:

> "geeksforgeeks --> GEEKSFORGEEKS"
> "Article written by  --> Shubham Singh"

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

class Replace2 {  
    constructor(value) {  
        this.value = value;  
    }  
      
    [Symbol.replace](string) {  
        return `${string}`;  
    }  
}
  
var val = new Replace2("geeksforgeeks");  
console.log("Before: " + val.value);  
console.log("After: " + val.value
        .toUpperCase().replace(val.value));  
   
var val2 = new Replace2("Few Users");  
console.log("Before: " + val2.value);  
console.log("After: " + "Millions of Users"
        .replace(val2.value));

chevron_right


Output:

> "Before: geeksforgeeks"
> "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

Reference: https://devdocs.io/javascript/global_objects/symbol/replace

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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.