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 January 2020.
Thuộc tính dữ liệu tĩnh Symbol.replace đại diện cho well-known symbol Symbol.replace. Các phương thức String.prototype.replace() và String.prototype.replaceAll() tra cứu symbol này trên đối số đầu tiên của chúng cho phương thức thay thế các chuỗi con khớp bởi đối tượng hiện tại.
Để biết thêm thông tin, xem RegExp.prototype[Symbol.replace](), String.prototype.replace(), và String.prototype.replaceAll().
Try it
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"
Giá trị
Well-known symbol Symbol.replace.
Property attributes of Symbol.replace | |
|---|---|
| Writable | no |
| Enumerable | no |
| Configurable | no |
Ví dụ
>Sử dụng Symbol.replace
js
class CustomReplacer {
constructor(value) {
this.value = value;
}
[Symbol.replace](string) {
return string.replace(this.value, "#!@?");
}
}
console.log("football".replace(new CustomReplacer("foo"))); // "#!@?tball"
Đặc tả
| Specification |
|---|
| ECMAScript® 2027 Language Specification> # sec-symbol.replace> |