JS: Create Regex Object
Regex Parts: Pattern and Flags
Regular Expression (aka regex, RegExp) has 2 parts:
- regex → specify a text pattern.
- flags → flags is used to tweak regex meaning or how the regex function behaves. e.g. ignore letter case.
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
- JS: RegExp Tutorial
- JS: Regex Functions
- JS: Create Regex Object
- JS: RegExp Syntax
- JS: RegExp Flag
- JS: Regex Replace String Dollar Sign
- JS: Regex Replace Function Args
- JS: RegExp (class)
- JS: RegExp Constructor
- JS: RegExp.prototype
- JS: String.prototype.search
- JS: String.prototype.match
- JS: String.prototype.matchAll
- JS: String.prototype.replace
- JS: String.prototype.replaceAll
- JS: RegExp.prototype.test
- JS: RegExp.prototype.exec