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.

Die statische Dateneigenschaft Symbol.replace repräsentiert das bekannte Symbol Symbol.replace. Die Methoden String.prototype.replace() und String.prototype.replaceAll() suchen dieses Symbol im ersten Argument, um die Methode zu finden, die Teilzeichenfolgen ersetzt, die mit dem aktuellen Objekt übereinstimmen.

Für weitere Informationen, siehe RegExp.prototype[Symbol.replace](), String.prototype.replace(), und String.prototype.replaceAll().

Probieren Sie es aus

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"

Wert

Das bekannte Symbol Symbol.replace.

Eigenschaften von Symbol.replace
Schreibbarnein
Aufzählbarnein
Konfigurierbarnein

Beispiele

Verwendung von 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"

Spezifikationen

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

Browser-Kompatibilität

Siehe auch