1.清除调原先高亮的标签
//获取html 文本中所有的背景色是yellow的span标签
const tempElement = document.createElement('div');
tempElement.innerHTML = prevContent
const spans = tempElement.querySelectorAll('span:where([style*="background-color: yellow"])');
console.log('spans::', spans);
//去除span标签,只保留文本
spans.forEach(span => {
const text = span.textContent;
span.replaceWith(text);
});
const modifiedHtmlString = tempElement.innerHTML;
console.log('modifiedHtmlString:', modifiedHtmlString);
2.匹配关键字,用span标签包裹,并设置标签色
//匹配多个敏感词,并高亮显示
const keywords = ['意义', '县', '教育'];
const regex = new RegExp(keywords.join('|'), 'gi');
const text = modifiedHtmlString
const highlightedText = text.replace(regex, match => `<span style="background-color: yellow">${match}</span>`);
console.log(highlightedText);
setNewDetail({ ...newDetail, imageText: highlightedText })
prevContent 是html 文本,
querySelectorAll 方法根据span标签的样式进行检索,是因为wangeditor 中加class或者id,都会被去掉