RegExp.prototype.source

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

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

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

Specifications

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

Browser compatibility

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
Node.js
source
"(?:)" for empty regexps
Line breaks and slashes are escaped
Prototype accessor property (ES2015)

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

See also