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 |
浏览器兼容性
加载中…