In the ever-evolving digital landscape, managing content efficiently and enhancing user experiences are paramount. Sitecore Content Hub is a great solution, empowering businesses to streamline their processes.
In this blog post, I will explore a piece of code I just finished that will highlight search results, thereby optimizing the user experience. You will see in the screenshot below, following a search it will add a yellow CSS class to any occurrences of the letter or word.

The ask was from the customer for an FAQ page for users. I created a new entity schema for this which consisted of:
- Question
- Answer
- Categories (Option List)
- Regions (Option List)

The representative schema is shown here and is really simple and was created using Azimutt which I blogged about recently.
Implementing JavaScript Code for Search Result Highlighting
To implement search result highlighting in Sitecore Content Hub, JavaScript can be utilized to manipulate the DOM elements.
This is all built using a React component, Roel a colleague of mine has a fantastic series on React components and Content Hub – https://www.restaurantofmistakenorders.com/.
The below could be used for any Content Hub search component. The following files are needed.
Index
import { createRoot } from "react-dom/client";
import HighlightTextOnSearch from "./HighlightTextOnSearch";
import { BaseContext } from "../../utils/context";
interface Context extends BaseContext{
config:{
searchIdentifier: string;
}
}
export default function createExternalRoot(container: HTMLElement) {
var root = createRoot(container);
return {
render(context: Context) {
root.render(<HighlightTextOnSearch context={context} searchIdentifier={context.config.searchIdentifier}/>);
},
unmount() {
root.unmount();
},
};
}
HighlightTextOnSearch
import { useEffect } from "react";
import { Constants } from "../../utils/constants";
import { BaseContext } from "../../utils/context";
interface HighlightTextOnSearchProps {
context: BaseContext;
searchIdentifier: string;
}
const HighlightTextOnSearch = ({
context,
searchIdentifier,
}: HighlightTextOnSearchProps) => {
useEffect(() => {
window.addEventListener(Constants.Events.SEARCH_FINISHED, onSearchFinished);
return () => {
window.removeEventListener(
Constants.Events.SEARCH_FINISHED,
onSearchFinished
);
};
}, []);
const onSearchFinished = (evt: Event): void => {
const { searchIdentifier: eventSearchIdentifier, fullText: eventFullText } = (
evt as CustomEvent<{
searchIdentifier: string;
fullText: string;
}>
).detail;
if (
eventSearchIdentifier ===
context.api.search.getEventSearchIdentifier(searchIdentifier)
) {
$('.highlight').contents().unwrap();
removeHighlightClass();
if (eventFullText.toLowerCase() !== "") {
var grid = document.querySelector(".css-14kr727-searchListWrapper");
const elements = grid?.querySelectorAll(".css-1jw6i8g-regular-htmlWrapper") ?? document.querySelectorAll(".css-1jw6i8g-regular-htmlWrapper");
elements.forEach(element => {
let innerHTML = element.innerHTML;
console.log("Before - " + innerHTML);
const fullText = escapeRegExp(eventFullText.toLowerCase());
const regex = new RegExp(`(${escapeRegExp(fullText)})(?![^<>]*>)`, "gi");
innerHTML = innerHTML.replace(regex, (match) => `<span class='highlight'>${match}</span>`);
console.log("After - " + innerHTML);
element.innerHTML = innerHTML;
});
}
}
};
const removeHighlightClass = () => {
console.log('Removing old highlights...');
const elementsWithHighlightClass = document.querySelectorAll('.highlight');
elementsWithHighlightClass.forEach(element => {
const parent = element.parentNode;
if (!parent)
return;
while (element.firstChild) {
parent.insertBefore(element.firstChild, element);
}
parent.removeChild(element);
});
console.log('Old highlights removed.');
};
function escapeRegExp(str: string) {
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
return (<></>);
};
export default HighlightTextOnSearch;
Basically, the code awaits the search-finished event to be sent. Then for each item in the search results it uses a regex to match the search terms and highlights that part.
Build the React component using your process and it should give you a file that you can upload as a portal asset.
Setting up the Content Hub component
We need to add the generated JavaScript as a portal asset.
Next wherever you want to use this will require a new external component. Add this to your search page and select the portal asset from the previous step.
Add the following CSS to the page
.highlight {
background-color: yellow;
}

That’s it, load your search page and enter a search term. Providing no errors in the console you should see the word test highlighted similar to below.


Conclusion
By integrating JavaScript to highlight search results in Sitecore Content Hub, businesses can significantly enhance the user experience.
This customization ensures that users can quickly identify relevant information, leading to increased user satisfaction and engagement.
As businesses continue to prioritize user-centric designs, implementing such features becomes essential, and JavaScript proves to be a valuable tool in this endeavour.








Leave a Reply