Open In App

JavaScript RegExp() Constructor

In JavaScript, the RegExp() constructor is used to create a RegExp object. This object can be created with or without the new keyword. The RegExp pattern can be passed in the constructor either in the literal notation or as a string. RegExp constructor is usually used when we want the p[attern to be decided dynamically.

Syntax:



RegExp(pattern, flag)
new RegExp(pattern, flag)

Parameters: The constructor takes two parameters where the flag is optional

Return Value: A RegExp object which contains the pattern string



Example 1: This example creates a new RegExp object with literal and string notation.




const reg1 = new RegExp(/ab/);
const reg2 = new RegExp("ab");
  
console.log(reg1);
console.log(reg1);

Output:

/ab/
/ab/

Example 2: This example uses RegExp object to compare matching values in string.




const str1 = "geeksforgeeks is a computer science platform"
  
const reg1 = new RegExp(/[g]/,'g');
  
console.log(str1.match(reg1));

Output: It is an array containing matching characters.

(2)['g', 'g']

Supported Browsers:

We have a complete list of Javascript RegExp expressions, to check those please go through this JavaScript RegExp Reference article.

Article Tags :