UNB/ CS/ David Bremner/ teaching/ cs2613/ books/ mdn/ Reference/ Regular expressions/ ""Character

A character escape represents a character that may not be able to be conveniently represented in its literal form.

Syntax

\f, \n, \r, \t, \v
\cA, \cB, …, \cz
\0
\^, \$, \\, \., \*, \+, \?, \(, \), \[, \], \{, \}, \|, \/

\xHH
\uHHHH
\u{HHH}

Note: , is not part of the syntax.

Parameters

Description

The following character escapes are recognized in regular expressions:

In Unicode-unaware mode, escape sequences that are not one of the above become identity escapes: they represent the character that follows the backslash. For example, \a represents the character a. This behavior limits the ability to introduce new escape sequences without causing backward compatibility issues, and is therefore forbidden in Unicode-aware mode.

In Unicode-unaware mode, ], {, and } may appear literally if it's not possible to parse them as the end of a character class or quantifier delimiters. This is a deprecated syntax for web compatibility, and you should not rely on it.

In Unicode-unaware mode, escape sequences within character classes of the form \cX where X is a number or _ are decoded in the same way as those with letters: \c0 is the same as \cP when taken modulo 32. In addition, if the form \cX is encountered anywhere where X is not one of the recognized characters, then the backslash is treated as a literal character. These syntaxes are also deprecated.

/[\c0]/.test("\x10"); // true
/[\c_]/.test("\x1f"); // true
/[\c*]/.test("\\"); // true
/\c/.test("\\c"); // true
/\c0/.test("\\c0"); // true (the \c0 syntax is only supported in character classes)

Examples

Using character escapes

Character escapes are useful when you want to match a character that is not easily represented in its literal form. For example, you cannot use a line break literally in a regex literal, so you must use a character escape:

const pattern = /a\nb/;
const string = `a
b`;
console.log(pattern.test(string)); // true

Specifications

Browser compatibility

See also