Regex
03 / 03

Common Patterns

Common Regex Patterns

A collection of battle-tested patterns for validating and extracting common data formats in JavaScript and TypeScript.

Validation Patterns

// Email (simplified but practical)
const emailRe = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
emailRe.test('user@example.com')   // true
emailRe.test('bad@')               // false

// URL (http/https)
const urlRe = /^https?:\/\/[\w-]+(\.[\w-]+)+([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?$/;

// IPv4 address
const ipv4Re = /^(25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)$/;

// Phone number (US, flexible format)
const phoneRe = /^\+?1?[-.\s]?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}$/;
phoneRe.test('(555) 123-4567')    // true
phoneRe.test('+1 555.123.4567')   // true

// Date YYYY-MM-DD
const dateRe = /^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/;

// Hex color  #rgb or #rrggbb
const hexColorRe = /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;

// URL-friendly slug
const slugRe = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;

// Password: min 8, uppercase, lowercase, digit, special char
const strongPasswordRe = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^a-zA-Z\d]).{8,}$/;

// Credit card (basic 16-digit check)
const ccRe = /^\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}$/;

Regex Flags

// g — global: find all matches (not just first)
'aaa'.match(/a/g)              // ['a', 'a', 'a']

// i — case-insensitive
/hello/i.test('Hello World')   // true

// m — multiline: ^ and $ match line start/end
const lines = 'first\nsecond\nthird';
lines.match(/^\w+/gm)          // ['first', 'second', 'third']

// s — dotAll: . matches newline too
/hello.world/s.test('hello\nworld')  // true (without s: false)

// u — unicode: enables full Unicode support
/\u{1F600}/u.test('\u{1F600}')  // true (emoji match)

// d — hasIndices: match.indices contains start/end positions
const result = /foo/d.exec('foobar');
console.log(result.indices[0]);  // [0, 3]

// Combining flags
/pattern/gim    // global + case-insensitive + multiline
new RegExp('pattern', 'gim')  // equivalent constructor form

Real-World Usage in JS/TS

// Strip HTML tags
const stripped = html.replace(/<[^>]*>/g, '');

// Trim multiple whitespace to single space
const normalized = str.replace(/\s+/g, ' ').trim();

// CamelCase to kebab-case
const kebab = str
  .replace(/([A-Z])/g, '-$1')
  .toLowerCase()
  .replace(/^-/, '');
// 'myVariableName' -> 'my-variable-name'

// Extract all numbers (including decimals and negatives)
const numbers = str.match(/-?\d+(\.\d+)?/g)?.map(Number) ?? [];

// Escape special regex characters for dynamic patterns
function escapeRegex(str: string): string {
  return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
const safe = escapeRegex('1 + 2 = 3');
new RegExp(safe).test('1 + 2 = 3');  // true

// Zod-style validation helper with regex
function validate(value: string, pattern: RegExp, message: string) {
  if (!pattern.test(value)) throw new Error(message);
  return value;
}
validate(email, /^[^\s@]+@[^\s@]+\.[^\s@]+$/, 'Invalid email');

// Template variable replacement
const template = 'Hello, {{name}}! You have {{count}} messages.';
const data = { name: 'Alice', count: '5' };
const output = template.replace(/\{\{(\w+)\}\}/g, (_, key) => data[key] ?? '');
// 'Hello, Alice! You have 5 messages.'

Keep your own version of these notes — editable, searchable, and organised by your stack.

Start free