Learn regex patterns, flags, exec, test, match, and replace for powerful string processing.
test and extract groups using matchAll.lastIndex to zero when executing global state matches.lastIndex property.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"); // trueZero 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>"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"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"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"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.
Parsing URL Strings with Named Groups
Parses database or web addresses using regular expression named capture groups to extract protocol and host names.
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 };
}Named capture groups document intent directly in patterns, making parsed string details easy to query.