Symbol.match
Symbol.match 靜態資料屬性代表 知名 Symbol Symbol.match。String.prototype.match() 方法會在其第一個引數上查詢此 Symbol,用於匹配輸入字串與當前物件的方法。此 Symbol 也用於確定一個物件是否應被 視為正則表示式。
有關更多資訊,請參閱 RegExp.prototype[Symbol.match]() 和 String.prototype.match()。
試一試
const regexp = /foo/;
// console.log('/foo/'.startsWith(regexp));
// Expected output (Chrome): Error: First argument to String.prototype.startsWith must not be a regular expression
// Expected output (Firefox): Error: Invalid type: first can't be a Regular Expression
// Expected output (Safari): Error: Argument to String.prototype.startsWith cannot be a RegExp
regexp[Symbol.match] = false;
console.log("/foo/".startsWith(regexp));
// Expected output: true
console.log("/baz/".endsWith(regexp));
// Expected output: false
值
知名 Symbol Symbol.match。
Symbol.match 的屬性特性 | |
|---|---|
| 可寫 | 否 |
| 可列舉 | 否 |
| 可配置 | 否 |
描述
此函式也用於識別 物件是否具有正則表示式的行為。例如,方法 String.prototype.startsWith()、String.prototype.endsWith() 和 String.prototype.includes() 會檢查它們的第一個引數是否為正則表示式,如果不是,則會丟擲 TypeError。現在,如果 match Symbol 被設定為 false(或除 undefined 以外的 假值),則表示該物件不應被用作正則表示式物件。
示例
將 RegExp 標記為非正則表示式
以下程式碼將丟擲 TypeError
js
"/bar/".startsWith(/bar/);
// Throws TypeError, as /bar/ is a regular expression
// and Symbol.match is not modified.
然而,如果您將 Symbol.match 設定為 false,該物件將被視為 非正則表示式物件。因此,startsWith 和 endsWith 方法將不會丟擲 TypeError。
js
const re = /foo/;
re[Symbol.match] = false;
"/foo/".startsWith(re); // true
"/baz/".endsWith(re); // false
規範
| 規範 |
|---|
| ECMAScript® 2026 語言規範 # sec-symbol.match |
瀏覽器相容性
載入中…