Emmanuel Akinfulubi

JavaScriptString

Escape a string for a regular expression in JavaScript

Advanced · 4 min read

A search box lets people type what they want to find, and you highlight every match on the page. To find every match you build a regular expression from what they typed. It works until someone searches for 1.5 or (note), and then it matches the wrong things or crashes.

In this tutorial you will write escapeRegExp, a small function that makes any text safe to put inside a regex, and use it to highlight every occurrence of a search term. This is a harder exercise, but we will start from zero: what goes wrong, why, and how a backslash fixes it. You should know how replace works with a regex and how $& puts back the match.

Characters with a special meaning

In a regular expression, some characters don't stand for themselves. They are metacharacters. Here are the ones that matter:

Metacharacters

. * + ? ^ $ { } ( ) | [ ] \

A dot means "any character". + means "one or more". Brackets make groups or sets. If you want a regex to match a real dot, you put a backslash in front of it: \. means "a dot, nothing else". Putting a backslash in front of a character like this is called escaping it.

Building a regex from text

new RegExp(text, flags) builds a regex from a string at run time. That is how you turn what a user typed into a pattern. But the string is read as a pattern, so any metacharacters in it keep their special meaning.

Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.

30 Escape a string for use in a regular expression

hard

Write escapeRegExp so that a needle typed by a user can be searched for as literal text. Then use it to highlight every occurrence of that needle.

Stuck? Three hints, smallest first
  1. 1. The characters that need escaping are . * + ? ^ $ { } ( ) | [ ] \.
  2. 2. A character class holds all of them; $& in the replacement puts the matched one back.
  3. 3. The backslash has to be escaped twice over: once for the string literal, once for the pattern.

Step 1: see it go wrong

Step 1

console.log(new RegExp('a.b').test('a.b')); // true
console.log(new RegExp('a.b').test('axb')); // true

test returns true when the pattern matches somewhere in the text. The user wanted to find a.b, but the pattern also matches axb, because the dot matched the x. Nothing warns you; it just finds too much.

Step 2: see it crash

Step 2

try {
  new RegExp('(');
} catch (e) {
  console.log(e.constructor.name); // 'SyntaxError'
  console.log(e.message);          // 'Invalid regular expression: /(/: Unterminated group'
}

An opening bracket on its own is an unfinished group, so building the regex throws a SyntaxError (the message shown is the wording node uses). A user typing one bracket into a search box could break your page.

Step 3: a backslash in a string costs two

Before writing the fix, there is one tricky detail. In a JavaScript string, the backslash is already special: '\n' means a newline. To get one real backslash character into a string, you type two:

Step 3

const BACKSLASH = '\\';
console.log(BACKSLASH.length); // 1

You typed two characters between the quotes, but the string holds one backslash.

Step 4: escape every metacharacter

The plan: find every metacharacter in the text and put a backslash in front of it. A character class, written with square brackets like [abc], matches any one of the characters inside. So we list all the metacharacters in one class and use the g flag to find every one. The replacement is a backslash followed by $&, the matched character.

Step 4

const escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
console.log(escapeRegExp('a.b'));        // a\.b (a, backslash, dot, b)
console.log(escapeRegExp('a.b').length); // 4
console.log(escapeRegExp('lagos 2025')); // 'lagos 2025'

Inside the class, \] and \\ are escaped so they count as a closing bracket and a backslash rather than ending the class. The replacement '\\$&' is a two-character string, a backslash and then $&, so every match comes out with a backslash in front of it. 'a.b' becomes the four characters a, \, ., b. Ordinary text has no metacharacters, so it comes back unchanged.

Step 5: the escaped pattern matches only the literal text

Step 5

const escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
console.log(new RegExp(escapeRegExp('a.b')).test('a.b')); // true
console.log(new RegExp(escapeRegExp('a.b')).test('axb')); // false

Now the dot means a dot, and axb no longer matches.

Step 6: highlight every match

With escaping in place, building the search regex is safe:

Step 6

const escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const highlightAll = (text, needle) =>
  text.replace(new RegExp(escapeRegExp(needle), 'g'), '[$&]');
console.log(highlightAll('a.b.c', '.'));    // 'a[.]b[.]c'
console.log(highlightAll('cost [x]', '[')); // 'cost [[]x]'
console.log('a.b.c'.replace(/./g, '[$&]')); // '[a][.][b][.][c]'

The search for . wraps only the two dots. Searching for a lone [ no longer throws. The last line shows what an unescaped dot would have done: wrap every character.

Step 7: check every metacharacter

Step 7

const escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const BACKSLASH = '\\';
console.log([...'.*+?^${}()|[]'].every((c) => escapeRegExp(c) === BACKSLASH + c)); // true
console.log(escapeRegExp(BACKSLASH) === BACKSLASH + BACKSLASH);                   // true

Each metacharacter, and the backslash itself, comes back with one backslash in front.

The full solution

Here is the complete answer: escapeRegExp, highlightAll and checks that the escaped pattern matches only the literal text and survives a stray bracket. Press Run and compare the escaped and unescaped highlight lines.

The answer

// Every regex metacharacter, escaped by putting a backslash in front of it.
// Inside a character class most of them lose their meaning already, but listing
// them all is what makes this readable rather than clever.
const escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');

const highlightAll = (text, needle) =>
  text.replace(new RegExp(escapeRegExp(needle), 'g'), '[$&]');

// One character. Written '\\' in source, because a lone backslash escapes
// whatever follows it.
const BACKSLASH = '\\';

console.log("escapeRegExp('a.b') :", escapeRegExp('a.b'));
console.log('does it still match "axb"?', new RegExp(escapeRegExp('a.b')).test('axb'));
console.log("highlightAll('a.b.c', '.') :", highlightAll('a.b.c', '.'));
console.log("unescaped, /./g gives      :", 'a.b.c'.replace(/./g, '[$&]'));

Output


      
11 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 11 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

11 checks

test('a dot comes back with a backslash in front of it', escapeRegExp('a.b'), 'a' + BACKSLASH + '.b');
test('which is one character longer than the input', escapeRegExp('a.b').length, 4);
test('the escaped pattern matches the literal text', new RegExp(escapeRegExp('a.b')).test('a.b'), true);
test('and nothing else', new RegExp(escapeRegExp('a.b')).test('axb'), false);
test('unescaped, the dot is a wildcard', new RegExp('a.b').test('axb'), true);
test('ordinary text is left completely alone', escapeRegExp('lagos 2025'), 'lagos 2025');
test('every metacharacter is covered', [...'.*+?^${}()|[]'].every((c) => escapeRegExp(c) === BACKSLASH + c), true);
test('including the backslash itself', escapeRegExp(BACKSLASH), BACKSLASH + BACKSLASH);
test('so a needle typed by a user is now safe to search for', highlightAll('a.b.c', '.'), 'a[.]b[.]c');
test('where the unescaped version would have matched everything', 'a.b.c'.replace(/./g, '[$&]'), '[a][.][b][.][c]');
test('and a stray bracket no longer throws a SyntaxError', highlightAll('cost [x]', '['), 'cost [[]x]');

Anything built with new RegExp(userInput) is a bug waiting for a customer to type (. It throws a SyntaxError on unbalanced brackets and silently matches the wrong thing on ., + or * — which is worse, because it looks like it works.

The double-escaping is the part that trips everyone. In the source, '\\$&' is a two-character string: one backslash, then $&. The backslash lands in the output pattern, and $& is expanded to the character that matched. Getting a single backslash into a string literal always costs two.

If a RegExp.escape exists in your runtime, use it. Until then this five-line function is the standard answer.

Common mistakes

  • Passing user text straight to new RegExp. A . matches anything and a ( throws. Escape it first.
  • Writing one backslash in the replacement. '\$&' is just '$&' to JavaScript, so nothing gets escaped. Write '\\$&'.
  • Escaping when you don't need a regex. If you only need a plain search and replace, replaceAll with a string needs no escaping at all.

Try it yourself

  1. Use escapeRegExp to count how many times '1+1' appears in '1+1=2, 1+1=2'.
  2. Change highlightAll so it ignores case. (Hint: the flags 'gi'.)
  3. Write startsWithText(text, prefix) that builds new RegExp('^' + escapeRegExp(prefix)) and test it with a prefix of '$5'.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.