2023 / 09 / 23
TIL: Escape JavaScript RegExp string

Create a regular expression from any string

javascript

Sometimes you try to use certain strings to create regular expressions.

The problem is these string might contain characters that have special meaning inside a RegExp. For example:

const myString = '[Hello?](World)!!!'

To escape it for safe use as a regex pattern, lodash provides escapeRegExp.

const myString = '[Hello?](World)!!!'
// "\\[Hello\\?\\]\\(World\\)!!!"

References