Advanced30 min read

Regular Expressions

Learn to match, search, and replace text patterns using JavaScript regular expressions.

What Are Regular Expressions?

Regular expressions (regex) are patterns used for matching, searching, and replacing text. They are a powerful tool built into JavaScript for working with strings.

Two ways to create a regex:

javascript
// Literal syntax (preferred for static patterns)
const regex1 = /hello/i;

// Constructor syntax (for dynamic patterns)
const regex2 = new RegExp('hello', 'i');

Common flags:

  • gGlobal: find all matches, not just the first
  • iCase-insensitive: match regardless of case
  • mMultiline: ^ and $ match start/end of each line
javascript
const text = 'Hello hello HELLO';
console.log(text.match(/hello/gi)); // ['Hello', 'hello', 'HELLO']

Regular expressions are used for validation (is this a valid email?), searching (find all phone numbers in text), and replacing (censor bad words, format text).

Pattern Syntax

Regex patterns are built from various special characters and sequences.

Character classes match categories of characters:

  • \d — any digit (0-9)
  • \w — any word character (letter, digit, underscore)
  • \s — any whitespace (space, tab, newline)
  • . — any character except newline
  • [abc] — any character in the set
  • [^abc] — any character NOT in the set

Quantifiers specify how many:

  • * — zero or more
  • + — one or more
  • ? — zero or one (optional)
  • {n} — exactly n times
  • {n,m} — between n and m times

Anchors match positions:

  • ^ — start of string (or line with m flag)
  • $ — end of string (or line with m flag)

Grouping and alternation:

  • () — group characters together
  • | — OR (alternation)
javascript
// Match a US phone number: 555-123-4567
const phone = /^\d{3}-\d{3}-\d{4}$/;
console.log(phone.test('555-123-4567')); // true

Escaping: To match a special character literally, prefix with \:

javascript
const price = /\$\d+\.\d{2}/; // matches $9.99, $100.00

Regex Methods

There are two sets of methods for working with regex: methods on RegExp objects and methods on strings.

RegExp methods:

javascript
const regex = /\d+/;

// test() — returns true or false
regex.test('abc123'); // true
regex.test('abc');    // false

// exec() — returns match array or null
regex.exec('abc123'); // ['123', index: 3, ...]

String methods that accept regex:

javascript
const text = 'Call 555-1234 or 555-5678';

// match() — find matches
text.match(/\d{3}-\d{4}/g); // ['555-1234', '555-5678']

// search() — find index of first match
text.search(/\d+/); // 5

// replace() — replace matches
text.replace(/\d/g, 'X'); // 'Call XXX-XXXX or XXX-XXXX'

// replaceAll() — replace all (needs g flag with regex)
'a.b.c'.replaceAll('.', '-'); // 'a-b-c'

// split() — split by pattern
'one, two,  three'.split(/,\s*/); // ['one', 'two', 'three']

Capture groups with parentheses:

javascript
const dateRegex = /(\d{4})-(\d{2})-(\d{2})/;
const match = '2024-01-15'.match(dateRegex);
console.log(match[1]); // '2024' (year)
console.log(match[2]); // '01'   (month)
console.log(match[3]); // '15'   (day)

Common Patterns

Here are some practical regex patterns you will encounter frequently.

Basic email validation:

javascript
const email = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
email.test('user@example.com');  // true
email.test('invalid-email');      // false

Phone numbers (various formats):

javascript
const phone = /^\+?\d{1,3}[-.\s]?\d{3}[-.\s]?\d{4}$/;

Extracting numbers from text:

javascript
const text = 'I have 3 cats and 12 dogs';
const numbers = text.match(/\d+/g).map(Number);
console.log(numbers); // [3, 12]

Replacing extra whitespace:

javascript
const messy = '  too   many   spaces  ';
const clean = messy.trim().replace(/\s+/g, ' ');
console.log(clean); // 'too many spaces'

When NOT to use regex:

  • Parsing HTML — use DOMParser or querySelector instead
  • Complex grammars — use a proper parser
  • Simple string operationsincludes(), startsWith(), endsWith() are clearer

The old saying goes: "Some people, when confronted with a problem, think 'I know, I'll use regular expressions.' Now they have two problems." Use regex when it is the right tool, but do not force it.

Regex in Action

html
<div id="output"></div>

<script>
  // Validation with test()
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  const isValid = emailRegex.test('user@example.com');

  // Extracting matches
  const text = 'Order #1234 and Order #5678';
  const orderNums = text.match(/#(\d+)/g);

  // Replacing with regex
  const censored = 'Call 555-1234 now!'.replace(/\d/g, 'X');

  // Splitting with regex
  const items = 'apple, banana;  cherry|date'.split(/[,;|]\s*/);

  const output = document.getElementById('output');
  output.innerHTML = `
    <p>Email valid: ${isValid}</p>
    <p>Order numbers: ${orderNums}</p>
    <p>Censored: ${censored}</p>
    <p>Items: [${items.join(', ')}]</p>
  `;
</script>

What does the regex /\d+/ match?

Ready to practice?

Create your free account to access the interactive code editor, run challenges, and track your progress.