//cardData带有标题和内容的html字符串,keyword需要匹配的关键字
let { title, content } = proxy.cardData;
//匹配关键字两字以上匹配,全局匹配
let regx = new RegExp("([" + proxy.keyword + "]{2,})", "g");
title = title.replaceAll(regx, '<text class="key_text">$1</text>');
let titleDom = document.getElementById("card_title" + proxy.cardData.id);
let bodyDom = document.getElementById("card_content" + proxy.cardData.id);
titleDom.innerHTML = title;
let div = document.createElement("div");
div.innerHTML = content;
content = div.textContent || div.innerText;
div.remove();
const len = content.length;
let size = 150;
//截取一段长文字中匹配的关键字的部分长度,显示在页面中
let index;
let regxS = new RegExp("([" + proxy.keyword + "]{2,})");
if (regxS.exec(content) === null) {
index = undefined;
} else {
index = regxS.exec(content).index - 2;
}
if (index && len > size && index !== -1) {
if (len - index > size) {
content = content.slice(index, index + size);
} else {
index - (len - size);
content = content.slice(len - size, len);
}
} else {
if (len > size) {
content = content.slice(0, size);
}
}
//对比配到的关键字替换html语义标签设置class,并在css中用deep设置出提示的高亮样式
content = content.replaceAll(regx, '<text class="key_text">$1</text>');
//添加到页面中
bodyDom.innerHTML = content;
匹配关键字高亮
最新推荐文章于 2024-09-13 14:34:15 发布