RegExp.prototype.toString()

RegExp 实例的 toString() 方法返回表示该正则表达式的字符串。

¥The toString() method of RegExp instances returns a string representing this regular expression.

Try it

语法

¥Syntax

js
toString()

参数

¥Parameters

没有任何。

¥None.

返回值

¥Return value

表示给定对象的字符串。

¥A string representing the given object.

描述

¥Description

RegExp 对象重写了 Object 对象的 toString() 方法;它不继承 Object.prototype.toString()。对于 RegExp 对象,toString() 方法返回正则表达式的字符串表示形式。

¥The RegExp object overrides the toString() method of the Object object; it does not inherit Object.prototype.toString(). For RegExp objects, the toString() method returns a string representation of the regular expression.

实际上,它读取正则表达式的 sourceflags 属性并返回 /source/flags 形式的字符串。toString() 返回值保证是可解析的正则表达式文字,尽管它可能与最初为正则表达式指定的文本不完全相同(例如,标志可能会重新排序)。

¥In practice, it reads the regex's source and flags properties and returns a string in the form /source/flags. The toString() return value is guaranteed to be a parsable regex literal, although it may not be the exact same text as what was originally specified for the regex (for example, the flags may be reordered).

示例

¥Examples

使用 toString()

¥Using toString()

以下示例显示 RegExp 对象的字符串值:

¥The following example displays the string value of a RegExp object:

js
const myExp = new RegExp("a+b+c");
console.log(myExp.toString()); // '/a+b+c/'

const foo = new RegExp("bar", "g");
console.log(foo.toString()); // '/bar/g'

空正则表达式和转义

¥Empty regular expressions and escaping

由于 toString() 访问 source 属性,空正则表达式返回字符串 "/(?:)/",并且诸如 \n 之类的行终止符被转义。这使得返回值始终是有效的正则表达式文字。

¥Since toString() accesses the source property, an empty regular expression returns the string "/(?:)/", and line terminators such as \n are escaped. This makes the returned value always a valid regex literal.

js
new RegExp().toString(); // "/(?:)/"

new RegExp("\n").toString() === "/\\n/"; // true

规范

Specification
ECMAScript Language Specification
# sec-regexp.prototype.tostring

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看