W3cubDocs

/JavaScript

RegExp.prototype.source

The source accessor property is a string containing the source text of the regex object, 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

const regex = /fooBar/ig;

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

Empty regular expressions and escaping

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

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

Specifications

Browser compatibility

Desktop Mobile Server
Chrome Edge Firefox Internet Explorer Opera Safari WebView Android Chrome Android Firefox for Android Opera Android Safari on IOS Samsung Internet Deno Node.js
source
1
12
1
4
5
1
4.4
18
4
10.1
1
1.0
1.0
0.10.0
empty_regex_string
6
12
38
No
15
5
≤37
18
38
14
4.2
1.0
1.0
0.10.0
escaping
73
12
38
10
60
6
73
73
38
52
6
11.0
1.0
12.0.0
prototype_accessor
48
12
41
4
35
1.3
48
48
41
35
1
5.0
1.0
6.0.0

See also

© 2005–2022 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/source