framework/js/lib/helpers/highlight.js

22 lines
557 B
JavaScript
Raw Normal View History

import truncate from '../utils/truncate';
export default function(string, phrase, length) {
if (!phrase) {
2015-06-03 16:40:56 +08:00
return string;
}
const regexp = phrase 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);
2015-06-03 16:40:56 +08:00
}
highlightedString = $('<div/>').text(highlightedString).html().replace(regexp, '<mark>$&</mark>');
return m.trust(highlightedString);
2015-06-03 16:40:56 +08:00
}