Last Updated : 07 Dec, 2024
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);
Syntax
let regex = new RegExp(pattern, flags);
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));
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));
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));
Key Points to Remember
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4