Debugging Techniques in JavaScript

From the JavaScript Regular Expressions cheat sheet · Debugging & Tools · verified Jul 2026

Debugging Techniques

Methods for testing and debugging patterns

javascript
// Test step by step
const pattern = /(\d{4})-(\d{2})-(\d{2})/
const input = "2024-03-15"

// 1. Test if it matches
console.log(pattern.test(input))  // true

// 2. Examine the match
const match = input.match(pattern)
console.log(match)
// ['2024-03-15', '2024', '03', '15', index: 0, ...]

// 3. Check all groups
match.forEach((group, i) => {
  console.log(\`Group \${i}: "\${group}"\`)
})

// Debug with verbose patterns
const verboseRegex = new RegExp([
  '(',           // Start group 1
    '\\d{4}',    // Year
  ')',           // End group 1
  '-',           // Literal dash
  '(',           // Start group 2
    '\\d{2}',    // Month
  ')',           // End group 2
].join(''), 'g')

// Test incrementally
const steps = [
  /\d/,          // Single digit
  /\d{4}/,       // Four digits
  /\d{4}-/,      // Four digits and dash
  /\d{4}-\d{2}/, // Add month
  /\d{4}-\d{2}-\d{2}/ // Full pattern
]

steps.forEach((step, i) => {
  console.log(\`Step \${i}: \${step.test(input)}\`)
})

// Log exec progression with global flag
const globalRegex = /\d+/g
let result
while (result = globalRegex.exec("a1b22c333")) {
  console.log({
    match: result[0],
    index: result.index,
    lastIndex: globalRegex.lastIndex
  })
}

// Performance testing
console.time('regex')
for (let i = 0; i < 100000; i++) {
  pattern.test(input)
}
console.timeEnd('regex')

// Create test suite
function testPattern(pattern, tests) {
  tests.forEach(({ input, expected, description }) => {
    const result = pattern.test(input)
    console.log(\`\${result === expected ? '✓' : '✗'} \${description}\`)
    if (result !== expected) {
      console.log(\`  Input: "\${input}"\`)
      console.log(\`  Expected: \${expected}, Got: \${result}\`)
    }
  })
}

// Visual debugging helper
function visualizeMatch(text, pattern) {
  const match = text.match(pattern)
  if (match) {
    const start = match.index
    const end = start + match[0].length
    console.log(text)
    console.log(' '.repeat(start) + '^' + '-'.repeat(match[0].length - 2) + '^')
    console.log(\`Matched: "\${match[0]}" at index \${start}\`)
  }
}

visualizeMatch("hello world", /world/)
// hello world
//       ^----^
// Matched: "world" at index 6
💡 Break complex patterns into smaller testable parts
⚡ Use online tools like regex101.com for visual debugging
📌 Test edge cases: empty strings, special characters
🟢 Create test suites for important patterns
debuggingtesting
Back to the full JavaScript Regular Expressions cheat sheet