GitHub

JavaScript Regex Cheatsheet

Regular Expression quick reference guide

Normal Characters

ExpressionDescription
.Any character excluding a newline or carriage return
[A-Za-z]Alphabet (both uppercase and lowercase)
[a-z]Lowercase alphabet
[A-Z]Uppercase alphabet
\d or [0-9]Digit
\D or [^0-9]Non-digit
_Underscore
\w or [A-Za-z0-9_]Alphabet, digit, or underscore
\W or [^A-Za-z0-9_]Inverse of \w (not alphabet, digit, or underscore)
\sSpace, tab, newline, or carriage return
\SInverse of \s (not space, tab, newline, or carriage return)

Whitespace Characters

ExpressionDescription
Space
\tTab
\nNewline
\rCarriage return
\sSpace, tab, newline, or carriage return

Boundaries

ExpressionDescription
^Start of string
$End of string
\bWord boundary

Notes:

  • How word boundary matching works:
  • At the beginning of the string if the first character is \w.
  • Between two adjacent characters within the string, if the first character is \w and the second character is \W.
  • At the end of the string if the last character is \w.

Matching

ExpressionDescription
foo|barMatch either foo or bar
foo(?=bar)Match foo if it's before bar
foo(?!bar)Match foo if it's not before bar
(?<=bar)fooMatch foo if it's after bar
(?<!bar)fooMatch foo if it's not after bar

Grouping and Capturing

ExpressionDescription
(foo)Capturing group; match and capture foo
(?:foo)Non-capturing group; match foo but without capturing foo
(foo)bar\1\1 is a backreference to the 1st capturing group; match foobarfoo

Notes:

  • Capturing groups are only relevant in the following methods:
  • string.match(regex)
  • string.matchAll(regex)
  • string.replace(regex, callback)
  • \n is a backreference to the nth capturing group. Capturing groups are numbered starting from 1.

Character Set

ExpressionDescription
[xyz]Either x, y, or z
[^xyz]Neither x, y, nor z
[1-3]Either 1, 2, or 3
[^1-3]Neither 1, 2, nor 3

Notes:

  • Think of a character set as an OR operation on the single characters that are enclosed between the square brackets [...].
  • Use ^ after the opening [ to 'negate' the character set.
  • Within a character set, . means a literal period.

Quantifiers

ExpressionDescription
{2}Exactly 2
{2,}At least 2
{2,7}At least 2 but no more than 7
*0 or more
+1 or more
?Exactly 0 or 1

Notes:

  • The quantifier goes after the expression to be quantified.

Characters That Require Escaping

ExpressionDescription

Outside a Character Set

ExpressionDescription
\.Period
\^Caret
\$Dollar sign
\|Pipe
\\Back slash
\/Forward slash
\(Opening bracket
\)Closing bracket
\[Opening square bracket
\]Closing square bracket
\{Opening curly bracket
\}Closing curly bracket

Inside a Character Set

ExpressionDescription
\\Back slash
\]Closing square bracket

Notes:

  • ^ must be escaped only if it occurs immediately after the opening [ of the character set.
  • - must be escaped only if it occurs between two alphabets or two digits.

References and Tools