JavaScript RegExp source
Syntax & Examples
RegExp.source property
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.
Syntax of RegExp.source
The syntax of RegExp.source property is:
RegExp.prototype.sourceThis source property of RegExp the text of the pattern. This property is read-only.
Return Type
RegExp.source returns value of type String.
✐ Examples
1 Using source to get the pattern text of a RegExp
In JavaScript, we can use the source property to get the text of the pattern from a RegExp object.
For example,
- We create a RegExp object
regexwith the pattern/hello/i. - We access the
sourceproperty ofregexto get the text of the pattern. - The result is stored in the variable
patternTextand we log it to the console.
JavaScript Program
const regex = /hello/i;
const patternText = regex.source;
console.log(patternText);Output
hello
2 Using source to compare patterns of different RegExp objects
In JavaScript, we can use the source property to compare the patterns of different RegExp objects.
For example,
- We create two RegExp objects
regex1andregex2with the patterns/abc/and/def/respectively. - We access the
sourceproperty of both objects. - We compare the patterns and log the results to the console.
JavaScript Program
const regex1 = /abc/;
const regex2 = /def/;
console.log(regex1.source); // 'abc'
console.log(regex2.source); // 'def'Output
abc def
3 Using source to create a new RegExp with the same pattern
In JavaScript, we can use the source property to create a new RegExp object with the same pattern as an existing one.
For example,
- We create a RegExp object
regex1with the pattern/xyz/. - We access the
sourceproperty ofregex1. - We create a new RegExp object
regex2using the pattern text obtained fromregex1. - We test the new pattern on the string
'xyz'and log the result to the console.
JavaScript Program
const regex1 = /xyz/;
const patternText = regex1.source;
const regex2 = new RegExp(patternText);
console.log(regex2.test('xyz'));Output
true
Summary
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.