Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

RegExp.escape

Escapes a string so it can be safely put into a regular expression.

Available since: ES2025

Syntax

RegExp.escape(str)

Parameters

ParameterTypeDescription
strstringText 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 c

Notes

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.

Thanks for reading!

Donate to the site — we work hard for you.