Symbol.replace

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2015.

Symbol.replace 这个属性指定了当一个字符串替换所匹配字符串时所调用的方法。String.prototype.replace() 方法会调用此方法。

更多信息,详见 RegExp.prototype[Symbol.replace]()String.prototype.replace()

尝试一下

class Replace1 {
  constructor(value) {
    this.value = value;
  }
  [Symbol.replace](string) {
    return `s/${string}/${this.value}/g`;
  }
}

console.log("foo".replace(new Replace1("bar")));
// Expected output: "s/foo/bar/g"
Symbol.replace 的属性特性
可写
可枚举
可配置

规范

Specification
ECMAScript® 2025 Language Specification
# sec-symbol.replace

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
Node.js
replace

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

参见