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