JavaScript Regular Expressions
JavaScript has built-in regex support. Mastering it unlocks powerful string processing — form validation, parsing, transformation — with concise code.
// Creating regex
const re1 = /pattern/flags; // literal (preferred — precompiled)
const re2 = new RegExp('pattern', 'flags'); // dynamic patterns
// Flags
// i - case insensitive
// g - global (all matches, not just first)
// m - multiline (^ $ match line boundaries)
// s - dotAll (. matches \n)
// Common methods
const str = 'Hello World 2026';
/world/i.test(str); // true — case insensitive
str.match(/\d+/); // ['2026'] — first match
str.match(/\d+/g); // ['2026'] — all matches
str.search(/\d/); // 12 — index of first match
str.replace(/World/, 'PHP'); // 'Hello PHP 2026'
str.split(/\s+/); // ['Hello', 'World', '2026']
Groups and References
// Capturing groups
const date = '2026-03-15';
const m = date.match(/(\d{4})-(\d{2})-(\d{2})/);
console.log(m[1], m[2], m[3]); // '2026' '03' '15'
// Named groups
const { groups: { year, month, day } } = date.match(
/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
);
console.log(year, month, day); // '2026' '03' '15'
// Back-references in replace
const str2 = 'first last';
str2.replace(/(\w+) (\w+)/, '$2 $1'); // 'last first'
str2.replace(/(?<f>\w+) (?<l>\w+)/, '$<l> $<f>'); // named refs
Practical Patterns
const validate = {
email: /^[\w.+-]+@[\w-]+\.[a-z]{2,}$/i,
phone_in: /^[6-9]\d{9}$/,
url: /^https?:\/\/[\w.-]+\.[a-z]{2,}/i,
slug: /^[a-z0-9]+(?:-[a-z0-9]+)*$/,
password: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&]).{8,}$/,
};
// Lookahead / lookbehind
'price: $100'.replace(/(?<=\$)\d+/, n => n * 1.18); // '118' (GST)
'100px'.match(/\d+(?=px)/)[0]; // '100' (lookahead)
Q: What is the difference between test() and match()?
test() returns a boolean — use it when you only need to know IF a pattern matches. match() returns the match array (or null) — use it when you need the matched text or captured groups. test() is slightly faster because it stops at the first match regardless of the g flag.
Comments (0)
No comments yet. Be the first!
Leave a Comment