Mark Oliver's World

Posted: 19/04/2021

Highlighting Search Terms

From my search page, you can search all the blog posts on this site.

As part of the results, I show a few characters either side of the found search term in the post.
It can also show multiple sections of a single post if multiple matches are found. e.g.

Search for "Blazor" and you see lots of extracts, here is the current top 1:

            Adding A Site Search ....markoliver.site 'search term'` e.g. https://www.google.com/search?q=site%3Ablog.markoliver.website+Blazor - Implement [Googles custom site search](https://support.google.com/programmable-search/answer/4513...  ...ink to jump to the posts, and highlight the search term on the result too. ### Solution So I need a Blazor page that has an input box and a button on it so you can enter the search term (for now its just a ...  ...er the search term (for now its just a simple pattern match), and a button to say go. I also need a Blazor component, that can render the results. In the back end, I need a searcher that will activate the s...  ...t this feature now, by clicking Search, or if you want to find all my posts that mention Blazor, go direct to the results here #### Update 15/10/2021 I forgot to remove case se...  ...), or if you want to find all my posts that mention Blazor, go direct to the results here #### Update 15/10/2021 I forgot to remove case sensitivity from the search, and also that the "en...
            
          

This is hard to read at a quick glance, so I need to add a highlight to the search term where it is found in the extract. This will make it more obvious we have multiple results in the post.

As I have a "DisplaySearchResult" Blazor component, this is easy to change.

First, we need to know what the original search term was, so Ill add a new Parameter to the search result component.

            
              [Parameter]     public string originalSearchTerm { get; set; } = null;
            
          

Then in the display code, add a span class around the found term text rendered to the screen. This requires the use of a MarkupString.
Give the span a css class of highlightSearchTerm and add

            ::deep .highlightSearchTerm {     color: black;     background-color: khaki;     padding: 0.2em; }
            
          

to the .razor.css file, and we now get the search results with the search term highlighted.

Note that I am making the search term black, with a lovely background khaki colour, but most important of all is the padding. This really makes the text standout.

Go have a look...


Thanks for reading this post.

If you want to reach out, catch me on Twitter!

I am always open to mentoring people, so get in touch.