Regex Patterns and Pitfalls

Here are some patterns you will use often for validation and text processing, along with tips for avoiding common regex pitfalls.

Common Patterns

Email (simplified)

const emailRegex = /^[\w.-]+@[\w.-]+\.\w{2,}$/;
emailRegex.test("user@example.com");  // true

URL (simplified)

const urlRegex = /^https?:\/\/[\w.-]+(?:\/[\w.-]*)*\/?$/;
urlRegex.test("https://example.com/path");  // true

Phone Number (US)

const phoneRegex = /^\(?(\d{3})\)?[-.\s]?(\d{3})[-.\s]?(\d{4})$/;
phoneRegex.test("(555) 123-4567");  // true
phoneRegex.test("555.123.4567");  // true

Date (YYYY-MM-DD format only)

const dateRegex = /^\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])$/;
dateRegex.test("2024-06-15");  // true

This checks structure and month/day ranges, but it does not validate real calendar dates (for example, leap years).

Password Validation

// At least 8 chars, 1 uppercase, 1 lowercase, 1 digit
const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/;
passwordRegex.test("Password1");  // true
passwordRegex.test("password");  // false

Trim Whitespace

const text = "  hello world  ";
text.replace(/^\s+|\s+$/g, "");  // "hello world"
// Or just use: text.trim()

Tips and Gotchas

Escaping Special Characters

Special regex characters need escaping: \ ^ $ . | ? * + ( ) [ ] { }

// Match literal "."
/\./.test("file.txt");  // true
/\./.test("filetxt");  // false

// Match literal "$100"
/\$\d+/.test("$100");  // true

The RegExp Constructor and Escaping

When you use the constructor, you pass the pattern as a string, so every backslash has to be escaped twice:

// These are equivalent:
const regex1 = /\d+/;
const regex2 = new RegExp("\\d+");

Regex Object State

A regex object with the g flag keeps state between calls:

const regex = /a/g;
const str = "ababa";

console.log(regex.test(str));  // true (finds first 'a')
console.log(regex.lastIndex);  // 1
console.log(regex.test(str));  // true (finds second 'a')
console.log(regex.lastIndex);  // 3
console.log(regex.test(str));  // true (finds third 'a')
console.log(regex.lastIndex);  // 5
console.log(regex.test(str));  // false (no more matches)
console.log(regex.lastIndex);  // 0 (reset)

Reset with regex.lastIndex = 0 or use a new regex each time.

Summary

Start simple and build up:

  1. Use literal characters when possible
  2. Add character classes for flexibility
  3. Use quantifiers for repetition
  4. Use anchors to match positions
  5. Use groups to capture parts