JavaScript RegExp()
Syntax & Examples


RegExp constructor

The RegExp constructor in JavaScript creates a new RegExp object for matching text with a pattern. It can be called with or without the 'new' keyword, and optionally accepts flags to modify the behavior of the pattern.


Syntax of RegExp

There are 4 variations for the syntax of RegExp() constructor. They are:

1.
new RegExp(pattern)

This constructor creates a new RegExp object using the given pattern.

2.
new RegExp(pattern, flags)

This constructor creates a new RegExp object using the given pattern and flags.

3.
RegExp(pattern)

This constructor creates a new RegExp object using the given pattern without the 'new' keyword.

4.
RegExp(pattern, flags)

This constructor creates a new RegExp object using the given pattern and flags without the 'new' keyword.



✐ Examples

1 Creating a RegExp object with a string pattern

In JavaScript, we can create a new RegExp object using a string pattern.

For example,

  1. We create a RegExp object regex with the pattern 'abc'.
  2. We test the pattern on the string 'abcdef' using the test method.
  3. We log the result to the console.

JavaScript Program

const regex = new RegExp('abc');
const result = regex.test('abcdef');
console.log(result);

Output

true

2 Creating a RegExp object with flags

In JavaScript, we can create a new RegExp object with a string pattern and flags to modify the behavior of the pattern.

For example,

  1. We create a RegExp object regex with the pattern 'abc' and the flag 'i' for case-insensitive matching.
  2. We test the pattern on the string 'ABCdef' using the test method.
  3. We log the result to the console.

JavaScript Program

const regex = new RegExp('abc', 'i');
const result = regex.test('ABCdef');
console.log(result);

Output

true

3 Creating a RegExp object without the 'new' keyword

In JavaScript, we can create a new RegExp object without using the 'new' keyword.

For example,

  1. We create a RegExp object regex with the pattern '123' and the flag 'g' for global matching.
  2. We use the exec method to find all matches in the string '123 123 123'.
  3. We log the results to the console.

JavaScript Program

const regex = RegExp('123', 'g');
const result = regex.exec('123 123 123');
console.log(result);

Output

[ '123', index: 0, input: '123 123 123', groups: undefined ]

Summary

In this JavaScript tutorial, we learned about RegExp constructor of RegExp: the syntax and few working examples with output and detailed explanation for each example.