Which Characters Need Escaping in a JavaScript Regular Expression Character Class?

In a JavaScript regular expression character class, all characters except the following are treated as literal characters:

  1. Caret ^;
  2. Minus/dash -;
  3. Closing Square Bracket ];
  4. Backslash \.

These characters have a special meaning inside a regular expression character class. Therefore, when you want to specify these characters to be matched literally inside a character class, you must escape them.

Using Caret Inside a RegExp Character Class

Inside a character class, the ^ character, when specified immediately after the opening [ negates the entire character class (i.e. it won't match any character listed in there). Due to its special meaning inside a character class, if you wish to use the caret character literally, you would have to escape it like so:

console.log(/[\^]/.test('^')); // true

Using Minus/Dash Inside a RegExp Character Class

Inside a character class, the - character is used to specify ranges of characters. Therefore, when you wish to use it literally, you must escape it like so:

console.log(/[\-]/.test('-')); // true

Using Closing Square Bracket Inside a RegExp Character Class

The opening/closing square bracket combination is used to specify a character class. When you wish to use them inside a character class literally, you need to only escape the closing square bracket. For example:

console.log(/[[]/.test('[')); // true
console.log(/[\]]/.test(']')); // true

Using Backslash Inside a RegExp Character Class

Backslash is the character used for escaping. If you try to use a single backslash (i.e. without escaping) inside a character class, it may result in:

  • The character that follows being escaped, or;
  • A SyntaxError when the character that immediately follows is the closing square bracket of the character class.

In case, you want to use the backslash character in the character class literally, you must escape it like so:

console.log(/[\\]/.test('\\')); // true

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.