Regex for Data Extraction and TransformationLesson 6.5
Building a regex-powered search and highlight function
dynamic regex from user input, escaping user input, highlight with replace, case-insensitive search, performance with large DOM, XSS prevention
Turn User Search Terms Into Safe Regex
Never pass raw user input directly into a RegExp constructor — metacharacters will break the pattern or introduce security issues. Always escape first.
function escapeRegex(str) {
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
function highlightMatches(text, searchTerm) {
if (!searchTerm.trim()) return text;
const escaped = escapeRegex(searchTerm.trim());
const re = new RegExp(`(${escaped})`, 'gi');
return text.replace(re, '<mark>$1</mark>');
}
XSS Warning
Only inject the highlighted result via innerHTML if the original text came from a trusted source.
