Open In App

JavaScript RegExp() Constructor

Last Updated : 07 Dec, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

The RegExp() constructor in JavaScript allows you to create a regular expression object that can be used to match patterns in strings. This method is particularly useful when you need to dynamically create regular expressions from strings or variables.

JavaScript
let pat = "hello";
let regex = new RegExp(pat, "i");
let res = regex.test("Hello, world!");

console.log(res);

Output
true
  • Pattern: We use “hello” as the pattern.
  • Flags: The “i” flag ensures that the matching is case-insensitive.
  • test() Method: The test() method is used to check if the string “Hello, world!” contains the pattern “hello”.

Syntax

let regex = new RegExp(pattern, flags);
  • pattern: The string pattern you want to match.
  • flags (optional): Flags to control the regular expression matching behaviour (e.g., g, i, m, etc.).

Real-World Use Cases of RegExp() Constructor

1. Dynamic Pattern Creation

If you need to create a regular expression based on a variable input, the RegExp() constructor allows you to dynamically generate patterns.

JavaScript
let inp = "abc";
let regex = new RegExp(inp, "g");
console.log("abcabc".match(regex));

Output
[ 'abc', 'abc' ]

2. Email Validation

You can use the RegExp() constructor to validate email formats dynamically.

JavaScript
let mail = "user@domain.com";
let pat = new RegExp("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}", "i");
console.log(pat.test(mail));

Output
true

3. Extracting Substrings

You can extract substrings that match a certain pattern.

JavaScript
let s = "The price is $100.";
let regex = new RegExp("\\$\\d+", "g");
console.log(s.match(regex));

Output
[ '$100' ]

Key Points to Remember

  • The RegExp() constructor is useful when you need to create a regular expression from a dynamic string.
  • You can specify flags such as g for global search, i for case-insensitive search, and m for multi-line search.
  • The RegExp() constructor can be combined with methods like test(), exec(), and match() to perform pattern matching and extraction.

Similar Reads

three90RightbarBannerImg
  翻译: