Skip to content

Commit

Permalink
Highlight search keywords on search result (vitessio#1654)
Browse files Browse the repository at this point in the history
* Highlight search keyword on search result

Signed-off-by: Manik Rana <Manikrana54@gmail.com>

* HIghlight results by each word in search query

Signed-off-by: Manik Rana <Manikrana54@gmail.com>

* Remove use of .innerHTML

Signed-off-by: Manik Rana <Manikrana54@gmail.com>

---------

Signed-off-by: Manik Rana <Manikrana54@gmail.com>
  • Loading branch information
Maniktherana authored Jan 23, 2024
1 parent 1000c82 commit fd1ef37
Showing 1 changed file with 17 additions and 0 deletions.
17 changes: 17 additions & 0 deletions layouts/partials/javascript.html
Original file line number Diff line number Diff line change
Expand Up @@ -182,10 +182,12 @@
const title = searchResultItem.querySelector('a.title');
title.setAttribute('href', doc.href);
title.textContent = doc.title;
highlightSearchTerm(title, doc.title, keywords);

const subtitle = searchResultItem.querySelector('a.subtitle');
subtitle.setAttribute('href', doc.href);
subtitle.textContent = doc.summary;
highlightSearchTerm(subtitle, doc.summary, keywords);

searchResultItem.addEventListener('click',
() => trackSearchResultClick(doc.href, query));
Expand All @@ -194,6 +196,21 @@
}
}

function highlightSearchTerm(element, content, keywords) {
// Split keywords by empty space
const keywordList = keywords.trim().split(/\s+/);
let highlightedContent = content;

keywordList.forEach(keyword => {
const regex = new RegExp(keyword, 'gi');
highlightedContent = highlightedContent.replace(regex, match => `<mark>${match}</mark>`);
});

// Replace with highlighted content
element.textContent = '';
element.appendChild(document.createRange().createContextualFragment(highlightedContent));
}

const lunrSearchEventCategory = 'Lunr Search';

function trackSearchEvent(searchTerm) {
Expand Down

0 comments on commit fd1ef37

Please sign in to comment.