JavaScript RegExp() Constructor (original) (raw)
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);
`
- **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));
`
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
- 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.