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
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'
