mirror of
https://github.com/flarum/framework.git
synced 2024-12-02 15:03:44 +08:00
22 lines
557 B
JavaScript
22 lines
557 B
JavaScript
import truncate from '../utils/truncate';
|
|
|
|
export default function(string, phrase, length) {
|
|
if (!phrase) {
|
|
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);
|
|
}
|
|
|
|
highlightedString = $('<div/>').text(highlightedString).html().replace(regexp, '<mark>$&</mark>');
|
|
|
|
return m.trust(highlightedString);
|
|
}
|