diff --git a/js/forum/src/components/discussions-search-results.js b/js/forum/src/components/discussions-search-results.js index ab6bed8dc..bf698439c 100644 --- a/js/forum/src/components/discussions-search-results.js +++ b/js/forum/src/components/discussions-search-results.js @@ -29,7 +29,7 @@ export default class DiscussionsSearchResults { return m('li.discussion-search-result', {'data-index': 'discussions'+discussion.id()}, m('a', { href: app.route.discussion(discussion, post && post.number()), config: m.route }, m('div.title', highlight(discussion.title(), string)), - post ? m('div.excerpt', highlight(truncate(post.contentPlain(), 100), string)) : '' + post ? m('div.excerpt', highlight(post.contentPlain(), string, 100)) : '' ) ); }) : '' diff --git a/js/lib/helpers/highlight.js b/js/lib/helpers/highlight.js index f01f5ba7e..75cd5fd20 100644 --- a/js/lib/helpers/highlight.js +++ b/js/lib/helpers/highlight.js @@ -1,13 +1,21 @@ -export default function(string, regexp) { - if (!regexp) { +import truncate from '../utils/truncate'; + +export default function(string, phrase, length) { + if (!phrase) { return string; } - if (!(regexp instanceof RegExp)) { - regexp = new RegExp(regexp, 'gi'); + const regexp = regexp instanceof RegExp ? phrase : new RegExp(phrase, 'gi'); + + let highlightedString = string; + let start = 0; + + if (length) { + start = Math.max(0, string.search(regexp) - length / 2); + highlightedString = truncate(highlightedString, length, start); } - return m.trust( - $('
').text(string).html().replace(regexp, '$&') - ); + highlightedString = $('
').text(highlightedString).html().replace(regexp, '$&'); + + return m.trust(highlightedString); } diff --git a/js/lib/utils/truncate.js b/js/lib/utils/truncate.js index 2acd77df0..c96ed70e6 100644 --- a/js/lib/utils/truncate.js +++ b/js/lib/utils/truncate.js @@ -1,6 +1,5 @@ -export default function truncate(string, length, start) { - start = start || 0; - string = string || ''; - - return (start > 0 ? '...' : '')+string.substring(start, start + length)+(string.length > start + length ? '...' : ''); +export default function truncate(string = '', length, start = 0) { + return (start > 0 ? '...' : '') + + string.substring(start, start + length) + + (string.length > start + length ? '...' : ''); }