Script Valley
Regex: Actually Useful Patterns
Regex for Data Extraction and TransformationLesson 6.3

Find and replace with regex using dynamic patterns

replace with function callback, dynamic replacement, conditional replace, casing transforms, template substitution

Replace Accepts a Function, Not Just a String

Replace with function

When the replacement depends on what was matched, pass a function as the second argument to replace().

// Title-case every word
'hello world'.replace(/\b\w/g, c => c.toUpperCase())
// => 'Hello World'

// Replace dates YYYY-MM-DD with human format
'Event on 2024-06-15'.replace(
  /(\d{4})-(\d{2})-(\d{2})/g,
  (_, y, m, d) => {
    const months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
    return `${months[+m-1]} ${+d}, ${y}`;
  }
)
// => 'Event on Jun 15, 2024'

Up next

Regex to parse CSV and TSV data rows

Sign in to track progress

Find and replace with regex using dynamic patterns โ€” Regex for Data Extraction and Transformation โ€” Regex: Actually Useful Patterns โ€” Script Valley โ€” Script Valley