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.source

This 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,

  1. We create a RegExp object regex with the pattern /hello/i.
  2. We access the source property of regex to get the text of the pattern.
  3. The result is stored in the variable patternText and 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,

  1. We create two RegExp objects regex1 and regex2 with the patterns /abc/ and /def/ respectively.
  2. We access the source property of both objects.
  3. 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,

  1. We create a RegExp object regex1 with the pattern /xyz/.
  2. We access the source property of regex1.
  3. We create a new RegExp object regex2 using the pattern text obtained from regex1.
  4. 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.