Skip to content

Regular Expression

In one line

A regular expression (regex) is a pattern used to match, search, and replace text.

In simple words

A regular expression (regex or regexp) is a pattern for matching text. It is written between slashes (/pattern/flags) or created with new RegExp(). Regex is used for validation (emails, phone numbers), searching, and replacing text.

Common patterns: \d (digit), \w (word character), \s (whitespace), . (any char), * (zero or more), + (one or more), ? (optional), [] (character set), () (group), | (or).

JavaScript provides String.match, String.replace, String.split (all accept regex), and RegExp.test (returns true/false), RegExp.exec (returns match details). Flags include g (global), i (case-insensitive), and m (multiline).

Example

javascript
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
console.log(emailRegex.test("ada@example.com")); // true
console.log(emailRegex.test("not-an-email")); // false

const result = "2024-01-15".match(/(\d{4})-(\d{2})-(\d{2})/);
console.log(result[1], result[2], result[3]); // "2024" "01" "15"

Regex patterns can validate and extract parts of strings.

Related terms

Related Resources

Related Lessons

Related Tools

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary