Text supplied at runtime can contain characters with special meaning in a regular expression. For example:
const input = "[Hello?](World)!!!"
Modern JavaScript provides RegExp.escape() for turning that text into a literal pattern:
const escaped = RegExp.escape(input)
// "\\[Hello\\?\\]\\(World\\)\\x21\\x21\\x21"
const pattern = new RegExp(escaped)
pattern.test(input)
// true
RegExp.escape() also handles edge cases that are easy to miss in a hand-written replacement. Check your runtime compatibility before using it.
For older runtimes, Lodash provides escapeRegExp():
const escaped = _.escapeRegExp(input)
// "\\[Hello\\?\\]\\(World\\)!!!"