How to highlight the results of a search?

Does anyone know if, and how, I can highlight the resultant text when I have a search function on a page?

image

4 Likes

There is no function to highlight text on the page. You can use a custom formatter for it.

Here a sample:

<script>
dmx.Formatters('string', {
  mark: function(str, search, ignoreCase) {
    return str.replace(new RegExp(search.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), ignoreCase ? 'gi' : 'g'), '<mark>$&</mark>');
  }
});
</script>
<input id="search" type="search">
<div dmx-html="myText.mark(search.value, true)"></div>

Will only work with dmx-html since it generates html.

4 Likes

Brilliant, thanks for the suggestion and fast response. I’ll have a play and see what I can achieve.

I do love Wappler.
Just a quick snapshot showing some great functionality…

Live Search with Clear (restores to original state)
A-Z Index links linked to Live Search
Anchor Links
Highlight Searched characters
as well as all the usual CRUD, layout, DB, etc
I know it’s all basic stuff, but it works really well. Just saying :smile:

3 Likes

@UKRiggers thank you for asking this question, and @patrick for the guidance - I’m going to try and implement this next week, too :slight_smile:

2 Likes

Thanks for the highlight text formatter which works very well. However, the text I am using contains images added by Summernote. I cannot work out how to edit the regex to exclude any code within angle brackets. Can anyone please help me with amending the custom highlighter to exclude any code within angle brackets?

This works well. Thanks @Patrick. But I am having one problem. When there is a search term entered it works perfectly.

But when the search box is empty it hilights between every letter? How can I prevent that?

Any help would be appreciated. I am using the exact script code provided by Patrick.

Solved it! Here is the code that skips the hilighting if search input is empty.

<script>
dmx.Formatters('string', {
  mark: function(str, search, ignoreCase) {
    if (!search) return str; // Return the original string if search term is empty
    return str.replace(new RegExp(search.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), ignoreCase ? 'gi' : 'g'), '<mark>$&</mark>');
  }
});
</script>

Note: Replace 'search' with your input ID

6 Likes