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);

`

**Syntax

let regex = new RegExp(pattern, flags);

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