JS搜索关键词高亮 ¶
js
/**
* JS搜索关键词高亮, 英文大小写都能搜到
* @param {string} content 内容
* @param {dtring} searchValue 关键词
* @param {string} color 关键词高亮颜色值,默认 red
* @returns {string} html
*/
const searchKeyValue = function (content: string, searchValue: string, color: string = 'red'): string{
const reg = new RegExp(searchValue.trim(),'gi');
let start = 0;
let end = 0;
let newStr = '';
let arr;
while((arr = reg.exec(content)) !== null){
end = arr.index;
newStr = newStr + content.slice(start,end);
start = end;
end = reg.lastIndex;
newStr = `${newStr}<span style="color: ${color}">${content.slice(start,end)}</span>`
start = end;
}
return newStr + content.slice(end);
}/**
* JS搜索关键词高亮, 英文大小写都能搜到
* @param {string} content 内容
* @param {dtring} searchValue 关键词
* @param {string} color 关键词高亮颜色值,默认 red
* @returns {string} html
*/
const searchKeyValue = function (content: string, searchValue: string, color: string = 'red'): string{
const reg = new RegExp(searchValue.trim(),'gi');
let start = 0;
let end = 0;
let newStr = '';
let arr;
while((arr = reg.exec(content)) !== null){
end = arr.index;
newStr = newStr + content.slice(start,end);
start = end;
end = reg.lastIndex;
newStr = `${newStr}<span style="color: ${color}">${content.slice(start,end)}</span>`
start = end;
}
return newStr + content.slice(end);
}