Understanding the Regular expression (Regex)

February 23, 2025

Explication

A Regular Expression (Regex) is used in JavaScript for pattern matching and text manipulation.

Creating regex

Enclosed between / or use the constructor function new RegExp() to create a regex. Example /\D/ or new RegExp(\D) using the constructor.

Using regex

MethodDescription
exec()Executes a search for a match in a string. It returns an array of information or null on a mismatch.
test()Tests for a match in a string. It returns true or false.
match()Returns an array containing all of the matches, including capturing groups, or null if no match is found.
matchAll()Returns an iterator containing all of the matches, including capturing groups.
search()Tests for a match in a string. It returns the index of the match, or -1 if the search fails.
replace()Executes a search for a match in a string, and replaces the matched substring with a replacement substring.
replaceAll()Executes a search for all matches in a string, and replaces the matched substrings with a replacement substring.
split()Uses a regular expression or a fixed string to break a string into an array of substrings.

Common patterns

PatternMeaning
\dMatches any digit (0-9)
\DMatches any non-digit
\wMatches any word character (letters, numbers, underscore)
\WMatches any non-word character
\sMatches any whitespace (spaces, tabs, newlines)
\SMatches any non-whitespace
^Start of string
$End of string
.Matches any character except newline
[A-Z]Matches any uppercase letter
[a-z]Matches any lowercase letter
{n,m}Matches between n and m occurrences

Patters flags

FlagMeaningUse Case
gGlobalMatch all occurrences, not just the first
iCase-InsensitiveMatch regardless of uppercase/lowercase
mMultiline^ and $ work for each line, not just the whole string
sDotall. matches newlines as well
uUnicodeAllows proper matching of Unicode (example, emojis)
yStickyMatch only at the exact position (controlled via lastIndex)