The JavaScript Symbol.replace symbol is responsible for identifying the method that substitutes the matched substring within a string.
Syntax
Example
[Symbol.replace](string).
Parameters
String.
Return value
A new string.
Browser Support
| Chrome | 32 |
|---|---|
| Safari | 8 |
| Firefox | 29 |
| Opera | 19 |
Example 1
Example
<script>
class Rep {
constructor(value) {
this.value = value;
}
[Symbol.replace](string) {
return `${string}`;
}
}
var r=new Rep("java");
document.writeln("Before: "+r.value);
document.writeln("After: "+"Example".replace(r.value));
</script>
Output:
Output
Before: java
After: Example
Example 2
Example
<script>
class Rep {
constructor(value) {
this.value = value;
}
[Symbol.replace](string) {
return `${string}`;
}
}
var r=new Rep("Example");
document.writeln("Before: "+r.value);
document.writeln("After: "+r.value.toUpperCase().replace(r.value));
</script>
Output:
Output
Before: Example
After: Example