I’m having some issues with searching a string in long text. I want to extract only searched text and highlight searched text with maybe 10-20 characters before it and after searched characters.
So basically what I want to achieve is, ex. from that text:
Hi there, I want to achieve a new goal to create a good search bar for
my app. It should be just as any other search bar.
So if I want to search “good search”, it should return something like:
…achieve a new goal to create a good search bar for my app. It
should be just…
So I just bolded the text, and took few characters from the left and right.
What would be a best way to do it? I tried something like:
const text = "Hi there, I want to achieve a new goal to create a good search bar for my app. It should be just as any other search bar."
const search_text = "good search"
const radius = 10;
// To determine where is the first character
const find_first = text.search(search_text)
const search_from = find_first - radius;
// To ensure that we are taking from first with length of searched text and additional ones
const search_to = find_first + search_text.length + radius
But still, this is only to determine how to check which characters to get. But how to list them and show with highlight?