I am searching for the title and description in my application and the task is to shorten search results. For example, if the description is too long (more than 2 lines) the result should be shortened to one or two lines of text with a found word highlighted.
Here's the example from algolia:
Here's what I've tried so far, but it's not working as expected:
const truncateHighlightedText = (
sentence,
searchExpression,
truncateLength
) => {
const pattern = new RegExp(
'\\b.{1,' +
truncateLength +
'}\\b' +
searchExpression +
'\\b.{1,' +
truncateLength +
'}\\b',
'i'
);
return sentence.match(pattern);
};
const sentence = "Testsdfgbsegsegsrewgserwfgvsrevfse ewrwer wergwregew erwgrewgwerg erwgwr eerg rg g er egr ew erger rtggrt tr ert tr tr tg tgr gtr gtr egrt rtg trg rg e eg";
const searchExpression = "egseg";
const truncateLength = 20;
const result = truncateHighlightedText(sentence, searchExpression, truncateLength);
console.log(result);
https://jsfiddle.net/dwr3qgs0/1/
What can be the best approach for this task?