JavaScript: Regular Expressions
Learn how to match, search, and transform text using the powerful pattern-matching syntax of regular expressions.
What are Regular Expressions?
A regular expression (regex) is a pattern that describes a set of strings. In JavaScript, regex is used to search, validate, extract, and replace text.
Regular Expressions
Regex is a mini-language for describing text patterns, one line of regex can replace dozens of if statements.
- Built into JavaScript, no imports needed
- Used by: form validation, search/replace, parsing, URL routing, log analysis
- A regex object has two parts: the pattern and optional flags
- Testing tool: use sites like regex101.com to build and test patterns interactively
What Regex Can Do
Validate an email and extract all phone numbers from a string in two lines.
Press Run to execute the code and see output here.
Creating Regex: Literal and Constructor
There are two ways to create a regex in JavaScript: the literal syntax using forward slashes, and the RegExp constructor for dynamic patterns.
Two Creation Syntaxes
Use the literal syntax for fixed patterns and the RegExp constructor when the pattern is built from a variable.
- Literal:
/pattern/flags, compiled at parse time, cleaner syntax - Constructor:
new RegExp("pattern", "flags"), built at runtime from strings - In the constructor, backslashes must be doubled:
\dbecomes"\\d" - Use the constructor when the search term comes from user input or a variable
Literal vs Constructor
Use literals for static patterns, use the constructor to build patterns from variables.
Press Run to execute the code and see output here.
Basic Patterns and Metacharacters
Most characters in a regex match themselves literally. Metacharacters have special meaning and must be escaped with a backslash if you want to match them literally.
Metacharacters
These characters have special meaning in regex, escape them with \\ to match literally.
.: any character except newline\d/\D: digit / non-digit\w/\W: word character (a-z, A-Z, 0-9, _) / non-word\s/\S: whitespace / non-whitespace\b: word boundary, position between a word char and a non-word char
Metacharacters
\\d matches digits, \\w matches word chars, and . matches anything except newline.
Press Run to execute the code and see output here.
Character Classes
Square brackets define a character class, a set of characters where any one member counts as a match. A ^ inside the brackets negates the class.
Character Classes [ ]
A character class matches exactly one character from the defined set.
[abc]: matches a, b, or c[a-z]: matches any lowercase letter (range)[A-Za-z0-9]: matches any alphanumeric character[^aeiou]: matches any character that is NOT a vowel (negated class)- Inside
[ ], most metacharacters lose their special meaning (except\,^,-,])
Character Classes
Match one character from a set, a range, or everything NOT in the set.
Press Run to execute the code and see output here.
Quantifiers
Quantifiers specify how many times the preceding element must occur for a match.
Quantifiers
Quantifiers control repetition, combine them with character classes for powerful patterns.
*: zero or more+: one or more?: zero or one (makes the element optional){n}: exactly n times{n,m}: between n and m times (inclusive)- Add
?after a quantifier to make it lazy (match as few as possible):+?
Quantifiers
Control how many times a pattern element must repeat to be a valid match.
Press Run to execute the code and see output here.
Anchors
Anchors do not match characters, they match positions in the string. Use them to ensure your pattern matches at the start, end, or a word boundary.
Anchors
Anchors lock the pattern to a position, essential for full-string validation.
^: start of the string (or start of a line with themflag)$: end of the string (or end of a line with themflag)\b: word boundary, between a word char and a non-word char- Without anchors, the pattern can match anywhere inside a longer string
Anchors: ^ $ \\b
Anchor patterns to positions to validate full strings or find whole words.
Press Run to execute the code and see output here.
Groups and Capturing
Parentheses () group part of a pattern and capture the matched text so you can extract it. Use (?:) for grouping without capturing.
Capturing Groups
Capturing groups let you extract specific parts of a match, names, dates, sub-patterns.
(pattern): capturing group, matched text saved at index 1, 2, …(?:pattern): non-capturing group, used for grouping only, no capture(?<name>pattern): named capturing group, access viamatch.groups.name- Back-references:
\1refers to the first captured group within the same pattern
Capturing Groups
Extract date parts with numbered groups or use named groups for readable access.
Press Run to execute the code and see output here.
Flags
Flags modify how the regex engine performs matching. They are placed after the closing slash in the literal syntax: /pattern/flags.
Common Flags
Flags are often combined, /pattern/gi finds all matches case-insensitively.
g: global, find all matches, not just the firsti: case-insensitive, A and a treated as equalm: multiline, ^ and $ match start/end of each line, not just the whole strings: dotAll, makes.also match newline charactersu: unicode, enables full Unicode matching and\u{...}escapes
Regex Flags
g finds all matches, i ignores case, m makes ^ and $ work per line.
Press Run to execute the code and see output here.
String Methods with Regex
JavaScript strings have built-in methods that accept regex patterns for searching, extracting, replacing, and splitting.
String + Regex Methods
These methods are the main way you use regex in everyday JavaScript code.
str.match(re): returns array of matches (all withg, first with capture groups otherwise)str.replace(re, replacement): replaces matches, use$1etc. to insert captured groupsstr.search(re): returns index of first match, or -1str.split(re): splits string by the regex patternre.test(str): returns true/falsere.exec(str): returns detailed match object with index and groups
String Methods with Regex
match extracts, replace transforms, search locates, split divides, exec gives full details.
Press Run to execute the code and see output here.
Common Patterns
These real-world patterns are used in form validation, parsing, and data extraction. Understanding them reinforces all the concepts covered in this lesson.
Practical Regex Patterns
Use these as starting points, adjust them to match your specific format requirements.
- Email: basic structure check, not a full RFC validation
- Phone: flexible format covering +92, dashes, and spaces
- URL: matches http and https URLs
- Always test regex against both valid and invalid inputs before shipping to production
Email, Phone, and URL Patterns
Practical validation patterns, test against both valid and invalid inputs.
Press Run to execute the code and see output here.
| Symbol | Meaning | Example |
|---|---|---|
. | Any character except newline | /c.t/ matches "cat", "cut" |
\d | Digit 0–9 | /\d+/ matches "123" |
\w | Word char (a-z A-Z 0-9 _) | /\w+/ matches "hello_1" |
\s | Whitespace | /\s+/ matches spaces, tabs |
^ | Start of string / line | /^Hello/ must start with Hello |
$ | End of string / line | /world$/ must end with world |
* | Zero or more | /a*/ matches "", "a", "aaa" |
+ | One or more | /a+/ matches "a", "aaa" not "" |
? | Zero or one (optional) | /colou?r/ matches "color" or "colour" |
{n,m} | Between n and m times | /\d{2,4}/ matches "12" to "1234" |
[abc] | One of a, b, or c | /[aeiou]/ matches any vowel |
[^abc] | NOT a, b, or c | /[^\d]/ matches non-digits |
() | Capturing group | /(\d{4})/ captures year |
(?:) | Non-capturing group | /(?:https?)/ groups no capture |
Knowledge Check
1. What is the difference between /pattern/ and new RegExp("pattern")?
2. What does the character class [^aeiou] match?
3. What does the + quantifier mean?
4. What does the g flag do?
5. What does regex.test(string) return?
6. Which string method returns an array of all matches when used with the g flag?
7. What do anchors ^ and $ match?