Mastering JavaScript Regular Expressions

Posted by Anonymous and classified in Computers

Written on in English with a size of 5.38 KB

JavaScript Regular Expressions: An Introduction

This concise and clear introduction to Regular Expressions (RegExp) in JavaScript covers their usage, modifiers, patterns, methods, and string integration.

Regular Expressions are powerful patterns used to match, search, and manipulate strings. In JavaScript, regular expressions are objects used with string methods to perform pattern matching.


RegExp Syntax Fundamentals

You can define a regular expression using literal notation:

const pattern = /expression/modifiers;

Or by using the RegExp constructor:

const pattern = new RegExp("expression", "modifiers");

RegExp Modifiers (Flags) Explained

Modifiers change how a Regular Expression behaves:

ModifierDescription
gGlobal match (find all matches, not just the first)
iCase-insensitive match
mMultiline match (^ and $ match start/end of lines)
sAllows . to match newline characters
uUnicode support (enables correct handling of Unicode characters)
ySticky match (matches from the exact position specified by lastIndex)

Example:

const regex = /hello/gi; // Matches 'hello' or 'Hello' globally

RegExp Patterns & Meta Characters

Meta characters give Regular Expressions their power by defining special patterns:

PatternDescription
.Any character except newline
\dAny digit (0-9)
\DAny non-digit character
\wAny word character (a-z, A-Z, 0-9, _)
\WAny non-word character
\sAny whitespace character
\SAny non-whitespace character
^Matches the start of the string
$Matches the end of the string
[...]Matches any single character inside the brackets
[^...]Matches any single character NOT inside the brackets
(a|b)Matches 'a' or 'b' (alternation)
a*Matches zero or more occurrences of "a"
a+Matches one or more occurrences of "a"
a?Matches zero or one occurrence of "a"
a{3}Matches exactly 3 occurrences of "a"
a{3,}Matches 3 or more occurrences of "a"
a{3,5}Matches between 3 and 5 occurrences of "a"

Core RegExp Methods

The test() Method

The test() method returns true or false if the pattern is found in the string.

/abc/.test("abcdef"); // true

The exec() Method

The exec() method returns an array with detailed match information or null if no match is found.

/abc/.exec("abcdef"); // ["abc", index: 0, input: "abcdef", groups: undefined]

String Methods Utilizing RegExp

Several built-in JavaScript string methods can accept a Regular Expression as an argument, enhancing their functionality:

MethodDescription
match()Returns an array of all matches (or null)
matchAll()Returns an iterator of all matches, including capture groups
search()Returns the index of the first match, or -1 if not found
replace()Replaces the first matched substring (or all with g flag)
replaceAll()Replaces all matched substrings (requires g flag)
split()Splits a string into an array of substrings using the RegExp pattern

Examples:

"hello123".match(/\d+/);        // ["123"]
"abc123".search(/\d/); // 3
"abc123".replace(/\d/g, "#"); // "abc###"
"one,two;three".split(/[,;]/); // ["one", "two", "three"]

Practical Applications of RegExp

Regular Expressions are incredibly useful for various tasks, including:

  • Validating input (e.g., email addresses, phone numbers, passwords)
  • Searching and extracting specific text from larger strings
  • Replacing or reformatting strings based on complex patterns
  • Splitting strings in sophisticated ways

Would you like to explore a real-world example, such as email or password validation?

Related entries: