You can create regular expressions in JS in one of two ways:
- Using regular expression literal -
/ab{2}/g
- Using the regular expression constructor -
new RegExp("ab{2}", "g")
.
Regular expression literals are constant, and can not be used with variables. This could be achieved using the constructor. The stracture of the RegEx constructor is
new RegExp(regularExpressionString, modifiersString)
You can embed variables as part of the regularExpressionString. For example,
var pattern="cd"
var repeats=3
new RegExp(`${pattern}{${repeats}}`, "g")
This will match any appearance of the pattern cdcdcd
.