search-plus-ts
Version:
Search always with machs and highlights.
16 lines (15 loc) • 725 B
JavaScript
//#region src/lib/highlight.ts
function highlightWordsTag(text, search, className, tagName = "span") {
if (search.trim() === "") return text;
const words = search.toLowerCase().trim().split(/\s+/);
const pattern = new RegExp(`\\b(${words.join("|")})\\b`, "gi");
return text.replace(pattern, (match) => `<${tagName} class="${className}">${match}</${tagName}>`);
}
function highlightWordsSymbols(text, search, symbol = "🔍") {
if (search.trim() === "") return text;
const words = search.toLowerCase().trim().split(/\s+/);
const pattern = new RegExp(`\\b(${words.join("|")})\\b`, "gi");
return text.replace(pattern, (match) => `${symbol} ${match}`);
}
//#endregion
export { highlightWordsSymbols, highlightWordsTag };