RegExp.escape
Escapes a string so it can be safely put into a regular expression.
Available since: ES2025
Syntax
RegExp.escape(str)Parameters
| Parameter | Type | Description |
|---|---|---|
| str | string | Text to be matched literally. |
Return value
stringA string with every special character escaped.
Examples
Dots and brackets lose their special meaning:
const query = 'a.b (c)';
const regex = new RegExp(RegExp.escape(query), 'g');
console.log('x a.b (c) y aXb c'.replace(regex, '[found]'));Output:
x [found] y aXb cNotes
Without escaping a dot in user text would match any character, and an unclosed bracket would throw a SyntaxError. The method is new; older browsers use str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&').
See also
- RegExp — A regular expression — a pattern for finding and replacing text.
- String.prototype.replaceAll — Replaces all occurrences of a substring with another string.
In the tutorial
- Regular expressions — Regular expressions in JavaScript for beginners: patterns, flags, character classes, testing, finding and replacing text.