Regular Expressions in JavaScript
Regular Expressions (regex) are powerful patterns used for matching, searching, and manipulating text. In JavaScript, they are implemented as objects with methods for various string operations.
Creating Regular Expressions
1. Literal Notation (Most Common)
const regex = /pattern/flags;
2. Constructor Notation
const regex = new RegExp('pattern', 'flags');
Flags (Modifiers)
i
- Case insensitiveg
- Global search (find all matches)m
- Multiline modes
- Dotall mode (dot matches newlines)u
- Unicode modey
- Sticky mode
// Examples
const caseInsensitive = /hello/i;
const globalSearch = /world/g;
const multiFlag = /test/gi; // case insensitive + global
Basic Patterns
Literal Characters
const regex = /hello/;
console.log(regex.test("hello world")); // true
console.log(regex.test("Hello world")); // false (case sensitive)
Special Characters (Need Escaping)
// These need to be escaped with \
const specialChars = /\.\*\+\?\^\$\{\}\(\)\|\[\]\\/;
Character Classes
Basic Character Sets
// Match any vowel
const vowels = /[aeiou]/;
console.log(vowels.test("hello")); // true
// Match digits
const digits = /[0-9]/;
console.log(digits.test("abc123")); // true
// Match hexadecimal characters
const hex = /[0-9a-fA-F]/;
Predefined Character Classes
const regex = {
digit: /\d/, // [0-9]
nonDigit: /\D/, // [^0-9]
word: /\w/, // [a-zA-Z0-9_]
nonWord: /\W/, // [^a-zA-Z0-9_]
whitespace: /\s/, // [ \t\r\n\f]
nonWhitespace: /\S/ // [^ \t\r\n\f]
};
console.log(/\d/.test("123")); // true
console.log(/\w/.test("hello")); // true
Negated Character Sets
// Match anything except vowels
const notVowels = /[^aeiou]/;
console.log(notVowels.test("aei")); // false
console.log(notVowels.test("abc")); // true (has 'b')
Quantifiers
Basic Quantifiers
// Zero or one (optional)
const optional = /colou?r/;
console.log(optional.test("color")); // true
console.log(optional.test("colour")); // true
// Zero or more
const zeroOrMore = /go*gle/;
console.log(zeroOrMore.test("ggle")); // true
console.log(zeroOrMore.test("google")); // true
// One or more
const oneOrMore = /go+gle/;
console.log(oneOrMore.test("ggle")); // false
console.log(oneOrMore.test("google")); // true
// Exact number
const exact = /\d{3}/; // exactly 3 digits
console.log(exact.test("123")); // true
console.log(exact.test("12")); // false
// Range
const range = /\d{2,4}/; // 2 to 4 digits
console.log(range.test("1")); // false
console.log(range.test("12")); // true
console.log(range.test("1234")); // true
Greedy vs Lazy Quantifiers
const text = "<div>content</div>";
// Greedy (default) - matches as much as possible
const greedy = /<.*>/;
console.log(text.match(greedy)[0]); // "<div>content</div>"
// Lazy - matches as little as possible
const lazy = /<.*?>/;
console.log(text.match(lazy)[0]); // "<div>"
Anchors and Boundaries
// Start of string
const start = /^Hello/;
console.log(start.test("Hello world")); // true
console.log(start.test("World Hello")); // false
// End of string
const end = /world$/;
console.log(end.test("Hello world")); // true
console.log(end.test("world Hello")); // false
// Word boundary
const boundary = /\bword\b/;
console.log(boundary.test("keyword")); // false
console.log(boundary.test("a word here")); // true
Groups and Capturing
Capturing Groups
const dateRegex = /(\d{2})-(\d{2})-(\d{4})/;
const match = "15-05-2023".match(dateRegex);
console.log(match[0]); // "15-05-2023" (full match)
console.log(match[1]); // "15" (day)
console.log(match[2]); // "05" (month)
console.log(match[3]); // "2023" (year)
Non-Capturing Groups
// (?:pattern) - group but don't capture
const nonCapturing = /(?:Mr|Ms|Mrs)\. (\w+)/;
const match = "Mr. Smith".match(nonCapturing);
console.log(match[1]); // "Smith" (only this is captured)
Named Capturing Groups
const namedRegex = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
const match = "2023-05-15".match(namedRegex);
console.log(match.groups.year); // "2023"
console.log(match.groups.month); // "05"
console.log(match.groups.day); // "15"
Lookaheads and Lookbehinds
// Positive lookahead - match 'q' followed by 'u'
const lookahead = /q(?=u)/;
console.log(lookahead.test("queen")); // true
// Negative lookahead - match 'q' not followed by 'u'
const negativeLookahead = /q(?!u)/;
console.log(negativeLookahead.test("Iraq")); // true
// Positive lookbehind - match 'd' preceded by 'c'
const lookbehind = /(?<=c)d/;
console.log(lookbehind.test("cd")); // true
// Negative lookbehind - match 'd' not preceded by 'c'
const negativeLookbehind = /(?<!c)d/;
console.log(negativeLookbehind.test("ad")); // true
Regex Methods
String Methods that Use Regex
1. match()
const text = "Hello world, hello universe";
const regex = /hello/gi;
const matches = text.match(regex);
console.log(matches); // ["Hello", "hello"]
2. matchAll()
(ES2020)
const text = "test1 test2 test3";
const regex = /test(\d)/g;
for (const match of text.matchAll(regex)) {
console.log(`Found: ${match[0]} with number: ${match[1]}`);
}
// Found: test1 with number: 1
// Found: test2 with number: 2
// Found: test3 with number: 3
3. replace()
const text = "John Smith";
const result = text.replace(/(\w+) (\w+)/, "$2, $1");
console.log(result); // "Smith, John"
// With function
const text2 = "price: 100, price: 200";
const result2 = text2.replace(/\d+/g, match => parseInt(match) * 1.1);
console.log(result2); // "price: 110, price: 220"
4. search()
const text = "Hello world";
const position = text.search(/world/);
console.log(position); // 6
5. split()
const text = "apple,banana,cherry";
const fruits = text.split(/,/);
console.log(fruits); // ["apple", "banana", "cherry"]
Regex Object Methods
1. test()
const regex = /\d{3}/;
console.log(regex.test("abc123")); // true
console.log(regex.test("abc")); // false
2. exec()
const regex = /\d+/g;
const text = "100 apples, 200 bananas";
let match;
while ((match = regex.exec(text)) !== null) {
console.log(`Found ${match[0]} at index ${match.index}`);
}
// Found 100 at index 0
// Found 200 at index 13
Practical Examples
1. Email Validation
function validateEmail(email) {
const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
return emailRegex.test(email);
}
console.log(validateEmail("test@example.com")); // true
console.log(validateEmail("invalid.email")); // false
2. Password Strength Checker
function checkPasswordStrength(password) {
const checks = {
length: /.{8,}/,
lowercase: /[a-z]/,
uppercase: /[A-Z]/,
digit: /\d/,
special: /[!@#$%^&*(),.?":{}|<>]/
};
let strength = 0;
for (const check in checks) {
if (checks[check].test(password)) strength++;
}
return strength;
}
console.log(checkPasswordStrength("Password123!")); // 5
3. URL Parser
function parseURL(url) {
const urlRegex = /^(https?):\/\/([^\/]+)(\/[^?#]*)?(\?[^#]*)?(#.*)?$/;
const match = url.match(urlRegex);
if (!match) return null;
return {
protocol: match[1],
host: match[2],
path: match[3] || '/',
query: match[4] || '',
hash: match[5] || ''
};
}
console.log(parseURL("https://example.com/path?query=1#section"));
4. HTML Tag Extractor
function extractTags(html) {
const tagRegex = /<(\w+)([^>]*)>/g;
const tags = [];
let match;
while ((match = tagRegex.exec(html)) !== null) {
tags.push({
tag: match[1],
attributes: match[2].trim()
});
}
return tags;
}
const html = '<div class="container"><p>Hello</p><img src="image.jpg"></div>';
console.log(extractTags(html));
5. Credit Card Formatter
function formatCreditCard(number) {
// Remove non-digits and limit to 16 characters
const clean = number.replace(/\D/g, '').substring(0, 16);
// Add space every 4 digits
return clean.replace(/(\d{4})(?=\d)/g, '$1 ');
}
console.log(formatCreditCard("1234567812345678")); // "1234 5678 1234 5678"
6. Template Engine (Simple)
function renderTemplate(template, data) {
return template.replace(/\{\{(\w+)\}\}/g, (match, key) => {
return data[key] || match;
});
}
const template = "Hello {{name}}, you have {{count}} messages.";
const data = { name: "John", count: 5 };
console.log(renderTemplate(template, data)); // "Hello John, you have 5 messages."
Advanced Tips
1. Performance Optimization
// Compile regex once if used repeatedly
const expensiveRegex = new RegExp('complex|pattern|here', 'gi');
function processText(text) {
return text.replace(expensiveRegex, 'REPLACED');
}
2. Dynamic Regex Construction
function createSearchRegex(searchTerm, caseSensitive = false) {
const flags = caseSensitive ? 'g' : 'gi';
// Escape special characters in search term
const escaped = searchTerm.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
return new RegExp(escaped, flags);
}
const searchRegex = createSearchRegex("hello.world");
console.log(searchRegex.test("Hello.world")); // true
3. Regex Debugging
function debugRegex(regex, text) {
console.log(`Regex: ${regex}`);
console.log(`Text: "${text}"`);
const match = regex.exec(text);
if (match) {
console.log('Match found:');
match.forEach((m, i) => {
console.log(` Group ${i}: "${m}"`);
});
} else {
console.log('No match found');
}
}
debugRegex(/(\d+)-(\w+)/, "123-abc");
Regular expressions are incredibly powerful but can become complex. Always test your regex thoroughly and consider using online tools like Regex101 for debugging and validation.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.