JavaScript RegExp() Constructor
Last Updated :
18 Apr, 2023
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
- pattern: This is the text to be matched or another RegExp object
- flag: It instructs which flags are to be checked when the match is performed
Return Value: A RegExp object which contains the pattern string
Example 1: This example creates a new RegExp object with literal and string notation.
Javascript
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.
Javascript
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:
- Chrome
- Edge
- Firefox
- Opera
- Safari
We have a complete list of Javascript RegExp expressions, to check those please go through this JavaScript RegExp Reference article.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...