The source property of the RegExp object in JavaScript returns a string containing the text of the pattern, excluding the forward slashes and any flags. This property is read-only.
The syntax of RegExp.source property is:
RegExp.prototype.source
This source property of RegExp the text of the pattern. This property is read-only.
RegExp.source returns value of type String
.
In JavaScript, we can use the source
property to get the text of the pattern from a RegExp object.
For example,
regex
with the pattern /hello/i
.source
property of regex
to get the text of the pattern.patternText
and we log it to the console.const regex = /hello/i;
const patternText = regex.source;
console.log(patternText);
hello
In JavaScript, we can use the source
property to compare the patterns of different RegExp objects.
For example,
regex1
and regex2
with the patterns /abc/
and /def/
respectively.source
property of both objects.const regex1 = /abc/;
const regex2 = /def/;
console.log(regex1.source); // 'abc'
console.log(regex2.source); // 'def'
abc def
In JavaScript, we can use the source
property to create a new RegExp object with the same pattern as an existing one.
For example,
regex1
with the pattern /xyz/
.source
property of regex1
.regex2
using the pattern text obtained from regex1
.'xyz'
and log the result to the console.const regex1 = /xyz/;
const patternText = regex1.source;
const regex2 = new RegExp(patternText);
console.log(regex2.test('xyz'));
true
In this JavaScript tutorial, we learned about source property of RegExp: the syntax and few working examples with output and detailed explanation for each example.