Skip to content

TIL: Escape JavaScript RegExp string

Create a regular expression from any string

1 min read

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:

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

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

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

References

More notes connected by topic, not algorithmic noise.