Dynamic Patterns in JavaScript

From the JavaScript Regular Expressions cheat sheet · Advanced Techniques · verified Jul 2026

Dynamic Patterns

Building regex dynamically

javascript
// Build regex from user input
function escapeRegex(string) {
  // Escape special regex characters
  return string.replace(/[.*+?^$'{}()|[\]\\]/g, '\\$&')
}

const userInput = "user.name"
const regex = new RegExp(escapeRegex(userInput))

// Build pattern with variables
const words = ['apple', 'banana', 'orange']
const pattern = new RegExp(`\\b(${words.join('|')})\\b`, 'gi')
// /\b(apple|banana|orange)\b/gi

// Template literal patterns
const year = '2024'
const dateRegex = new RegExp(`${year}-\\d{2}-\\d{2}`)

// Conditional patterns
function buildValidator(options) {
  let pattern = '^'

  if (options.uppercase) pattern += '(?=.*[A-Z])'
  if (options.lowercase) pattern += '(?=.*[a-z])'
  if (options.digit) pattern += '(?=.*\\d)'
  if (options.special) pattern += '(?=.*[@$!%*?&])'

  pattern += `.{${options.minLength},}$`
  return new RegExp(pattern)
}

// Function to create word boundary pattern
function wordBoundary(word) {
  return new RegExp(`\\b${escapeRegex(word)}\\b`, 'gi')
}

// Create pattern from array
function anyOf(items) {
  const escaped = items.map(escapeRegex)
  return new RegExp(`(${escaped.join('|')})`, 'g')
}
💡 Always escape user input to prevent regex injection
⚡ Use template literals for complex pattern building
📌 Remember to double-escape in string literals
🟢 Build reusable pattern factories for common needs
dynamicbuilding

More JavaScript tasks

Back to the full JavaScript Regular Expressions cheat sheet