需求:标题搜索keyword,对返回数据str中存在的所有关键词进行高亮显示
解决方案:
a计划(对keyword字符串进行循环,在str中出现keyword的地方插入HTML标签):
1.插入HTML标签函数
/**
* @param {String} target 需高亮显示的字符串
* @param {String} str 原始字符串
*/
showHigh(target,str){
let positions = [];
let pos = str.indexOf(target);
while (pos > -1) {
positions.push(pos);
pos = str.indexOf(target, pos + 1);
}
positions = positions.map((item, index) => {
return (item += 30 * index);
});
positions.forEach((item, index) => {
str =
str.slice(0, item) + "<span class='higthStr'>" + str.slice(item);
str =
str.slice(0, item + 23 + target.length) +
"</span>" +
str.slice(item + 23+ target.length);
});
return str
}
// 30为插入标签字符串length 23为开始标签length
2.AJ