JavaScript Regular Expressions Syntax Cheat Sheet
Regular Expressions (RegEx) are patterns used to match character combinations in strings. In JavaScript, regular expressions are objects that can be created using the RegExp
constructor or by using a literal notation.
Creating Regular Expressions
Literal Notation
Constructor Notation
Common Flags
g
: Global search.i
: Case-insensitive search.m
: Multi-line search.s
: Dot matches newline characters (ES2018).u
: Unicode; treat a pattern as a sequence of Unicode code points.y
: Sticky; matches only from the index indicated by thelastIndex
property of this regular expression.
Special Characters
.
: Matches any single character except newline.\d
: Matches any digit (0-9).\D
: Matches any non-digit.\w
: Matches any word character (alphanumeric & underscore).\W
: Matches any non-word character.\s
: Matches any whitespace character.\S
: Matches any non-whitespace character.\b
: Matches a word boundary.\B
: Matches a non-word boundary.^
: Matches the beginning of the string or line.$
: Matches the end of the string or line.
Quantifiers
*
: Matches 0 or more occurrences of the preceding element.+
: Matches 1 or more occurrences of the preceding element.?
: Matches 0 or 1 occurrence of the preceding element.{n}
: Matches exactlyn
occurrences of the preceding element.{n,}
: Matchesn
or more occurrences of the preceding element.{n,m}
: Matches betweenn
andm
occurrences of the preceding element.
Character Classes
[abc]
: Matches any one of the charactersa
,b
, orc
.[^abc]
: Matches any character excepta
,b
, orc
.[a-z]
: Matches any character froma
toz
.[A-Z]
: Matches any character fromA
toZ
.[0-9]
: Matches any digit from0
to9
.
Grouping and Alternation
(abc)
: Matches the exact sequenceabc
.a|b
: Matches eithera
orb
.(a|b)
: Matches eithera
orb
.
Assertions
(?=...)
: Positive lookahead assertion.(?!...)
: Negative lookahead assertion.(?<=...)
: Positive lookbehind assertion (ES2018).(?<!...)
: Negative lookbehind assertion (ES2018).
Escaping Special Characters
Use a backslash (\
) to escape special characters.
Using Regular Expressions in JavaScript
test()
: Tests for a match in a string. Returns true
or false
.
exec()
: Executes a search for a match in a string. Returns an array of results or null
.
String Methods with Regular Expressions
-
match()
: Returns an array containing all matches ornull
. -
matchAll()
: Returns an iterator of all results matching a string against a regular expression, including capturing groups. -
replace()
: Replaces matches in a string with a replacement. -
search()
: Searches for a match in a string and returns the index of the match. -
split()
: Splits a string into an array of substrings.
Examples
Validate Email
Extract Domain from URL
Match All Words
This cheat sheet provides an overview of JavaScript regular expressions syntax and usage. Regular expressions are a powerful tool for text processing and data validation in JavaScript.