RegExp.prototype.source

RegExp 实例的 source 访问器属性返回一个包含此正则表达式的源文本的字符串,两侧不带两个正斜杠或任何标志。

¥The source accessor property of RegExp instances returns a string containing the source text of this regular expression, without the two forward slashes on both sides or any flags.

Try it

描述

¥Description

从概念上讲,source 属性是正则表达式文字中两个正斜杠之间的文本。该语言要求返回的字符串被正确转义,以便当 source 两端与正斜杠连接时,它将形成可解析的正则表达式文字。例如,对于 new RegExp("/")source\\/,因为如果它生成 /,则结果文字变成 ///,这是行注释。同样,所有 行终止符 都将被转义,因为行终止符字符会破坏正则表达式文字。对其他字符没有要求,只要结果是可解析的即可。对于空正则表达式,返回字符串 (?:)

¥Conceptually, the source property is the text between the two forward slashes in the regular expression literal. The language requires the returned string to be properly escaped, so that when the source is concatenated with a forward slash on both ends, it would form a parsable regex literal. For example, for new RegExp("/"), the source is \\/, because if it generates /, the resulting literal becomes ///, which is a line comment. Similarly, all line terminators will be escaped because line terminator characters would break up the regex literal. There's no requirement for other characters, as long as the result is parsable. For empty regular expressions, the string (?:) is returned.

示例

¥Examples

使用源码

¥Using source

js
const regex = /fooBar/gi;

console.log(regex.source); // "fooBar", doesn't contain /.../ and "gi".

空正则表达式和转义

¥Empty regular expressions and escaping

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

new RegExp("\n").source === "\\n"; // true, starting with ES5

规范

Specification
ECMAScript Language Specification
# sec-get-regexp.prototype.source

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看