Sunday, September 22, 2024
Google search engine
HomeLanguagesJavascriptJavaScript RegExp() Constructor

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

  • 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 = "neveropen 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.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments