Regular Expressions in JavaScript
Regular Expressions (RegEx) are powerful patterns used to search, match, and manipulate text. From form validation to parsing, they are an indispensable tool in every JavaScript developer's toolkit.
What is a Regular Expression?
A Regular Expression (regex or regexp) is a sequence of characters that forms a search pattern. You use it to test whether a string contains a certain pattern, extract matching parts, or replace text based on a rule.
Think of it as a supercharged indexOf().
Where indexOf() only finds exact substrings, regex can match
patterns — like "any 5-digit number", "an email address", or "a word that starts with
a capital letter".
Creating a Regular Expression
JavaScript gives you two ways to create a regex:
// 1️⃣ Literal notation — use when pattern is known at write-time (preferred)
const re1 = /hello/i; // pattern between / / followed by optional flags
// 2️⃣ Constructor notation — use when pattern is built dynamically at runtime
const word = "hello";
const re2 = new RegExp(word, "i"); // RegExp(pattern, flags)
console.log(re1.test("Hello World")); // true (case-insensitive)
console.log(re2.test("Hello World")); // true
/pattern/flags
— it is cleaner, avoids escaping backslashes twice, and has no overhead. Use
new RegExp() only when the pattern needs to be composed
from a variable at runtime.
Regex Flags
Flags modify how the pattern is applied. They are placed after the closing
/ of a literal regex, or as the second argument of
RegExp(). Multiple flags can be combined.
A matches a.
^ and $ match the start/end of each line, not
just the whole string.. match newline
characters too.indices on
match results showing start/end positions (ES2022).const str = "Cat cat CAT";
// g — global: all matches
console.log(str.match(/cat/g)); // ["cat"] (only lowercase)
// gi — global + case-insensitive: every occurrence
console.log(str.match(/cat/gi)); // ["Cat", "cat", "CAT"]
// m — multiline: ^ / $ per line
const text = "first\nsecond\nthird";
console.log(text.match(/^\w+/gm)); // ["first","second","third"]
Character Classes & Quantifiers
These are the fundamental building blocks of every regex pattern:
| Syntax | Meaning | Example |
|---|---|---|
. |
Any character except newline | /c.t/ → "cat", "cut", "c3t" |
\d |
Any digit (0–9) | /\d+/ → "42", "007" |
\D |
Any non-digit | /\D/ → "a", " ", "!" |
\w |
Word character [a-zA-Z0-9_] | /\w+/ → "hello_World" |
\W |
Non-word character | /\W/ → "@", " ", "-" |
\s |
Whitespace (space, tab, newline) | /\s+/ → trims gaps |
[abc] |
Character set — matches a, b, or c | /[aeiou]/ → vowels |
[^abc] |
Negated set — anything NOT in set | /[^0-9]/ → non-digits |
^ |
Start of string (or line with m) |
/^Hello/ |
$ |
End of string (or line) | /world$/ |
* |
0 or more of the preceding | /ab*/ → "a", "ab", "abbb" |
+ |
1 or more of the preceding | /ab+/ → "ab", "abbb" |
? |
0 or 1 (optional) | /colou?r/ → "color" or "colour" |
{n} |
Exactly n times | /\d{4}/ → "2025" |
{n,m} |
Between n and m times | /\d{2,4}/ → "12", "1234" |
// Match a UK postcode format (simplified): AB12 3CD
const postcode = /^[A-Z]{1,2}\d{1,2}\s\d[A-Z]{2}$/i;
console.log(postcode.test("SW1A 1AA")); // true
console.log(postcode.test("hello")); // false
// Extract all numbers from a sentence
const sentence = "I have 3 cats and 12 fish.";
console.log(sentence.match(/\d+/g)); // ["3", "12"]
// Optional character — matches both "colour" and "color"
console.log(/colou?r/.test("color")); // true
console.log(/colou?r/.test("colour")); // true
Groups & Alternation
Groups let you treat multiple characters as a unit, capture them for later use, or create "or" conditions with alternation.
match()[1].
| or quantifiers.match().groups.name.
// Capturing group — extract year, month, day from a date string
const dateStr = "2025-07-21";
const dateRe = /(\d{4})-(\d{2})-(\d{2})/;
const m = dateStr.match(dateRe);
console.log(m[1], m[2], m[3]); // "2025" "07" "21"
// Named capturing group — cleaner access
const namedRe = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
const { year, month, day } = dateStr.match(namedRe).groups;
console.log(year, month, day); // "2025" "07" "21"
// Alternation — match "cat" or "dog"
const petRe = /cat|dog/gi;
console.log("I have a Cat and a Dog".match(petRe)); // ["Cat", "Dog"]
// Non-capturing group with quantifier
const repeatRe = /(?:ha){3}/;
console.log(repeatRe.test("hahaha")); // true
console.log(repeatRe.test("haha")); // false
JavaScript Regex Methods
Regex can be used through RegExp prototype methods and String methods. Here are the six you'll use most often:
true or
false. The fastest way to check if a pattern
exists in a string.
null. Without g
flag, also includes capture groups.g flag.-1. Ignores the g
flag.$1 etc. to reference capture groups.
const email = "user@example.com";
const emailRe = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
// test() — validate
console.log(emailRe.test(email)); // true
// search() — find position
console.log("Hello World".search(/world/i)); // 6
// replace() — swap text ($1 = first captured group)
const date = "2025-07-21";
console.log(date.replace(/(\d{4})-(\d{2})-(\d{2})/, "$3/$2/$1"));
// "21/07/2025"
// replaceAll equivalent using /g flag
const str = "foo bar foo baz foo";
console.log(str.replace(/foo/g, "qux")); // "qux bar qux baz qux"
// split() — split on multiple separators at once
const csv = "one, two;three|four";
console.log(csv.split(/[,;|]\s*/));
// ["one", "two", "three", "four"]
// matchAll() — all matches with groups
const text = "#ff0000 and #00ff00";
for (const hit of text.matchAll(/#([a-f0-9]{6})/gi)) {
console.log(hit[0], hit[1]); // "#ff0000" "ff0000" then "#00ff00" "00ff00"
}
Common Real-World Regex Patterns
These are patterns you'll reach for again and again in real projects:
// Email (simplified)
const emailRe = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
// URL (http & https)
const urlRe = /https?:\/\/[\w\-.]+(\/[\w\-./?%&=]*)?/;
// Indian mobile number (+91 optional)
const mobileRe = /^(\+91[\s-]?)?[6-9]\d{9}$/;
// Strong password (min 8 chars, upper, lower, digit, special)
const pwdRe = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&]).{8,}$/;
// Hex color code (#fff or #ffffff)
const hexRe = /^#([a-f0-9]{3}|[a-f0-9]{6})$/i;
// ISO date YYYY-MM-DD
const isoDateRe = /^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/;
// Strip HTML tags from a string
const noTagsRe = /<[^>]*>/g;
console.log("<b>Hello</b>".replace(noTagsRe, "")); // "Hello"
// Trim extra whitespace
console.log(" hello world ".replace(/\s+/g, " ").trim());
// "hello world"
(?=...) syntax above is a lookahead
assertion.
(?=.*[A-Z]) means "the string must contain at least one
uppercase letter somewhere" — without consuming any characters. Lookaheads are zero-width
assertions that add conditions to a match without advancing the cursor.
Where Regex is Used in Real Projects
Regular expressions show up everywhere in production JavaScript code:
Try It Yourself — Regex Tester
.,
+, ?,
(, ) when you want
them to mean the literal character. Use a backslash: \.
matches a real dot, while . matches any character.
Which regex flag makes ^ and
$ match the start and end of each line
(not just the whole string)?
- A Regular Expression is a pattern used to search, extract, or replace text in a string.
- Create regex with literal syntax
/pattern/flagsornew RegExp(pattern, flags). - Key flags: g (all matches), i (case-insensitive), m (multiline), s (dot-all).
- Character classes (
\d,\w,[abc]) and quantifiers (+,*,{n,m}) build powerful patterns. - Capturing groups
(...)and named groups(?<name>...)let you extract specific parts of a match. - Use
test()to validate,match()/matchAll()to extract,replace()to transform, andsplit()to divide strings.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.