Symbol.match

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2020 年 1 月⁩ 起,所有主流瀏覽器均已支援。

Symbol.match 靜態資料屬性代表 知名 Symbol Symbol.matchString.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,該物件將被視為 非正則表示式物件。因此,startsWithendsWith 方法將不會丟擲 TypeError

js
const re = /foo/;
re[Symbol.match] = false;
"/foo/".startsWith(re); // true
"/baz/".endsWith(re); // false

規範

規範
ECMAScript® 2026 語言規範
# sec-symbol.match

瀏覽器相容性

另見