JS: Create Regex Object

By Xah Lee. Date: .

Regex Parts: Pattern and Flags

Regular Expression (aka regex, RegExp) has 2 parts:

Create Regex Object

RegExp object are created in 2 ways

/regex/flags

Literal expression. This is convenient. 〔see RegExp Tutorial

RegExp(str, flagsStr)

This is more general, and can be used to construct regex from string at runtime. 〔see RegExp Constructor

💡 TIP: if your regex contains slash, use the RegExp(str, flagsStr) form, so you can avoid backslash to escape the slash. e.g. "text containing url".match(RegExp("https?://[a-z]+", "g")) . If your regex contains many backslash, e.g. \d, use the /regex/flags form to avoid escaping string.

JavaScript. Regular Expression