Skip to content
Related Articles

Related Articles

JavaScript | Symbol.replace Property
  • Last Updated : 25 Mar, 2020

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:




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')));

Output:

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

Example 2:




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

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
Recommended Articles
Page :