Skip to content

TIL: Escape a string for a JavaScript regular expression

Safely use arbitrary text as a literal JavaScript regular-expression pattern.

1 min read

Text supplied at runtime can contain characters with special meaning in a regular expression. For example:

JavaScript
const input = "[Hello?](World)!!!"

Modern JavaScript provides RegExp.escape() for turning that text into a literal pattern:

JavaScript
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():

JavaScript
const escaped = _.escapeRegExp(input)
// "\\[Hello\\?\\]\\(World\\)!!!"

References

More posts connected by shared tags.