Skip to content

Instantly share code, notes, and snippets.

@splenwilz
Last active April 5, 2024 09:23
Show Gist options
  • Save splenwilz/5b200e809bfb8d6f9d34bfa438575b88 to your computer and use it in GitHub Desktop.
Save splenwilz/5b200e809bfb8d6f9d34bfa438575b88 to your computer and use it in GitHub Desktop.
This TypeScript function, `highlightKeyword`, is designed to highlight occurrences of keywords within HTML content. It removes existing <span> tags before highlighting, and it avoids replacing text within specific HTML attributes such as href, alt, or title. To use this function, simply pass the content, query (keyword or keywords separated by c…
/**
* Highlights occurrences of keywords within content.
* @param {string} content - The content in which to highlight keywords.
* @param {string} query - The keyword or keywords to highlight (comma-separated).
* @param {boolean} removeSpans - Whether to remove existing <span> tags before highlighting. Default is true.
* @returns {string} The content with highlighted keywords.
*/
export function highlightKeyword(content: string, query: string, removeSpans = true): string {
if (!query) return content;
// Remove all <span> tags from the content
content = removeSpans ? content.replace(/<span[^>]*>|<\/span>/g, '') : content;
// Split the query string by commas
const queries = query.split(',');
// Process each keyword
queries.forEach(keyword => {
// Escape special characters in the keyword
const escapedQuery = keyword.trim().replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
// Construct regex pattern for the keyword
const regex = new RegExp(`(>|^)([^<]*?)(?:<a [^>]*>|<img [^>]*>|title="[^"]*"|alt="[^"]*")*?\\b(${escapedQuery})\\b(?:<\/a>|<\/img>)*?([^<]*?)(<|$)`, 'gi');
// Highlight occurrences of the keyword
content = content.replace(
regex,
'$1$2<b class="highlighted" style="color: rgba(220, 139, 1, 1);">$3</b>$4$5'
);
});
return content;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment