HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

Escape a regular expression in JavaScript

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
escapejavascriptexpressionregular

Problem

Regular expressions are a powerful tool for pattern matching and string manipulation. However, when you need to use a string as a regular expression, you need to escape special characters to avoid syntax errors.
Luckily, escaping a string for use in a regular expression is not hard, but it requires, you guessed it, a regular expression! By using the String.prototype.replace() method, you can escape special characters in a string.
The regular expression that you can then use to escape special characters is /[.*+?^${}()|[\]\\]/g. This regular expression matches all the special characters used in regular expressions. Then, each match is replaced with the escaped version of the character using \\$&.

Solution

const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\%%CODEBLOCK_0%%amp;');

escapeRegExp('(test)'); // \\(test\\)


The regular expression that you can then use to escape special characters is /[.*+?^${}()|[\]\\]/g. This regular expression matches all the special characters used in regular expressions. Then, each match is replaced with the escaped version of the character using \\$&.

Code Snippets

const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');

escapeRegExp('(test)'); // \\(test\\)

Context

From 30-seconds-of-code: escape-reg-exp

Revisions (0)

No revisions yet.