JavaScript

Escape a literal value for a regular expression

Use RegExp.escape when a dynamic string must be matched literally inside a regular expression. It protects punctuation from becoming pattern syntax and handles edge cases beyond a basic replacement of metacharacters.

Worked example

Node.js example · save as example.mjs and run node example.mjs

const search = "a.b";
const pattern = new RegExp(RegExp.escape(search), "g");
console.log("a.b axb a.b".replace(pattern, "hit"));

How it works

The escaped pattern matches the actual dot rather than any character. This keeps a user’s literal search separate from the regular-expression language. Construct the pattern only after escaping each dynamic literal portion, while keeping intentional pattern syntax under your control.

Limits and mistakes

Check engine support because this API is newer than many common string methods. Escaping a literal does not make an arbitrarily complex surrounding expression efficient. For simple literal replacement, replaceAll with a string is usually clearer.

Check the result

Expect hit axb hit. Include brackets, backslashes, and dollar signs in tests. If an older target lacks RegExp.escape, use a maintained compatible implementation or avoid regex construction.

Sources

Reference documentation for the behavior used in this guide: