JavaScript Regular Expressions
Learn regex patterns, flags, exec, test, match, and replace for powerful string processing.
TL;DR
- 01Define literal patterns with slashes or construct them using variables.
- 02Verify expressions with
testand extract groups usingmatchAll. - 03Replace target strings dynamically by passing matching replacement patterns.
Tips
- 01Use named capture groups to make complex regular expressions much easier to read and maintain.
- 02Create fresh regex instances or reset
lastIndexto zero when executing global state matches.
Warnings
- 01Remember that global regular expressions maintain state between execution runs via the
lastIndexproperty. - 02Escape user-provided variables with backslashes before constructing dynamic patterns to prevent parsing failures.
Creating Patterns
Regex literalDefines static patterns using forward slash brackets.
const pattern = /hello/;
console.log(pattern.test("hello world")); // trueRegExp constructorCompiles patterns dynamically at runtime from string variables.
const word = "hello";
const pattern = new RegExp(word);
console.log(pattern.test("say hello")); // trueCharacter classesMatches specific characters from defined character sets.
/[aeiou]/.test("hello"); // true
/[0-9]/.test("abc123"); // trueString anchorsEnforces starting and ending boundaries on checks.
/^hello/.test("hello world"); // true
/world$/.test("hello world"); // trueQuantifiers
Zero or moreMatches zero or more occurrences using the asterisk operator.
/a*b/.test("b"); // true
/a*b/.test("aaab"); // trueOne or moreMatches one or more occurrences using the plus operator.
/a+b/.test("ab"); // true
/a+b/.test("b"); // falseOptional quantifierMarks elements as optional using the question mark operator.
/colou?r/.test("color"); // true
/colou?r/.test("colour"); // trueLazy matchingAppends ? to quantifiers to match minimal characters.
const greedy = "<a><b>".match(/<.+>/)[0]; // "<a><b>"
const lazy = "<a><b>".match(/<.+?>/)[0]; // "<a>"Flags and Methods
Regex flagsSpecifies search parameters like case-insensitivity or global parsing.
/hello/i.test("HELLO"); // true
"hi hi".match(/hi/g); // ["hi", "hi"]exec() detailsReturns match arrays along with capture groups.
const res = /(\w+)@(\w+)/.exec("user@test.com");
// res[1] === "user", res[2] === "test"Replacing and Testing
String replaceReplaces search results with new replacement string values.
"hello world".replace(/hello/, "hi"); // "hi world"String replaceAllReplaces all matching entries globally when using g flag expressions.
"hi hi".replaceAll(/hi/g, "hello"); // "hello hello"Common Regex Patterns
Validation samplesValidates formats like phone numbers or simple emails.
/^\d{3}-\d{3}-\d{4}$/.test("123-456-7890"); // trueWhitespace collapseCollapses duplicate spaces and trims outer edges.
const clean = " a b ".replace(/\s+/g, " ").trim();
// clean === "a b"In Practice
Parses database or web addresses using regular expression named capture groups to extract protocol and host names.
- 01Write a validation regular expression pattern specifying named capture groups.
- 02Execute the pattern against the target string address parameters.
- 03Confirm that a valid match details response was retrieved.
- 04Extract captured keys from the matched groups property index.
- 05Return the structured details object back to callers.
function parseConnection(str) {
const regex =
/^(?<proto>https?):\/\/(?<host>[^/]+)$/;
const match = regex.exec(str);
if (!match) return null;
const { proto, host } = match.groups;
return { proto, host };
}FAQ
Use the RegExp constructor when compiling patterns dynamically from variables. Use literal patterns for static definitions. Literals compile during script loading and catch syntax bugs early.
Greedy quantifiers match as many characters as possible. Lazy quantifiers append a question mark to match as few as possible. For example, .*? performs lazy matches.
Use String.prototype.matchAll() with the g flag. This returns an iterator containing complete match details and capture groups. Regular match() drops capture group indices.
The replace() method defaults to updating only the first match without a global g flag. Use replaceAll() or include the global flag to substitute all instances.
Parentheses wrap sections of patterns to create capture groups. Retrieve them using index offsets like match[1]. Alternatively, use (?<name>) syntax to query named capture groups.