在线文档教程

regExp.source

regExp.source

source属性返回一个值为当前正则表达式对象的模式文本的字符串,该字符串不会包含正则字面量两边的斜杠以及任何的标志字符。

| RegExp.prototype.source属性的属性特性 |

|:----|

| Writable | no |

| Enumerable | no |

| Configurable | yes |

示例

使用source

var regex = /fooBar/ig; console.log(regex.source // "fooBar", doesn't contain /.../ and "ig".

清空正则表达式并转义

从ECMAScript 5开始,该source属性不再为空的正则表达式返回一个空字符串。而是"(?:)"返回字符串。另外,行终止符(例如“\ n”)现在被转义了。

new RegExp().source; // "(?:)" new RegExp('\n').source === '\n'; // true, prior to ES5 new RegExp('\n').source === '\\n'; // true, starting with ES5

规范

SpecificationStatusComment
ECMAScript 3rd Edition (ECMA-262)StandardInitial definition. Implemented in JavaScript 1.2. JavaScript 1.5: source is a property of a RegExp instance, not the RegExp object.
ECMAScript 5.1 (ECMA-262)The definition of 'RegExp.prototype.source' in that specification.StandardThe source property for empty regular expressions now returns "(?:)" instead of an empty string. A definition for the escaping behavior has been added.
ECMAScript 2015 (6th Edition, ECMA-262)The definition of 'RegExp.prototype.source' in that specification.Standardsource is now a prototype accessor property rather than an instance's own data property.
ECMAScript Latest Draft (ECMA-262)The definition of 'RegExp.prototype.source' in that specification.Draft

浏览器兼容性

FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support(Yes)(Yes)(Yes)(Yes)(Yes)(Yes)
"(?:)" for empty regexpsNo support?38 (38)??(Yes)
Escaping??38 (38)???
Prototype accessor property??41 (41)???

FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support(Yes)(Yes)(Yes)(Yes)(Yes)(Yes)(Yes)
"(?:)" for empty regexps???38.0 (38)???
Escaping???38.0 (38)???
Prototype accessor property???41.0 (41)???