stackademic

The leading education platform for anyone with an interest in software development.

JavaScript Regular Expressions

Match, capture, and replace text patterns with the RegExp API

Overview

A regular expression describes a pattern of characters used to search and transform strings. JavaScript supports them through literal /pattern/flags syntax and the RegExp constructor. Methods like test, match, matchAll, and replace cover most matching and rewriting needs.

Syntax / Usage

Flags change matching behavior: g (global), i (case-insensitive), m (multiline), and s (dot matches newlines). Parentheses create capture groups, and (?<name>...) creates named groups.

const re = /(\d{4})-(\d{2})-(\d{2})/ // literal
const dynamic = new RegExp('\\bword\\b', 'gi') // from a string

re.test('2026-07-03') // true

const match = '2026-07-03'.match(re)
console.log(match[1], match[2], match[3]) // '2026' '07' '03'

// Named groups
const named = /(?<year>\d{4})-(?<month>\d{2})/
const { groups } = '2026-07'.match(named)
console.log(groups.year) // '2026'

Examples

Replace using a callback to transform each match:

const text = 'items: 3, price: 9'
const doubled = text.replace(/\d+/g, (n) => Number(n) * 2)
console.log(doubled) // 'items: 6, price: 18'

Iterate every match with capture groups using matchAll:

const log = 'GET /a 200, POST /b 404'
const re = /(GET|POST) (\/\w+) (\d{3})/g

for (const [, method, path, status] of log.matchAll(re)) {
  console.log(method, path, status)
}
// GET /a 200
// POST /b 404

Validate a simple email shape (basic, not RFC-complete):

const isEmail = (s) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s)
console.log(isEmail('ada@example.com')) // true
console.log(isEmail('nope')) // false

Common Mistakes

  • Reusing a /g regex with test—the lastIndex advances between calls and skips matches
  • Forgetting to escape special characters like ., +, or ( when matching literals
  • Writing catastrophic backtracking patterns (nested quantifiers) that hang on long input
  • Using match without g and expecting all matches instead of the first with groups
  • Trying to parse deeply nested structures like HTML with regex

See Also

array-methods functions javascript-error-handling