Files
Todo/lib/utils.ts

24 lines
727 B
TypeScript

/**
* Highlights matching text in a string by wrapping matches with a marker
* @param text - The text to search in
* @param query - The search query to highlight
* @returns The text with highlighted matches wrapped in <mark> tags
*/
export function highlightText(text: string, query: string): string {
if (!query.trim() || !text) {
return text
}
const regex = new RegExp(`(${escapeRegExp(query)})`, 'gi')
return text.replace(regex, '<mark>$1</mark>')
}
/**
* Escapes special regex characters in a string
* @param string - The string to escape
* @returns The escaped string safe for use in RegExp
*/
function escapeRegExp(string: string): string {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
}