js高亮文本
高亮文本
const inputs = ["这是一个普通文本,包含关键字测试。",'<p style="font-size: 10px">这是一个<span>GVM</span> <strong>测试</strong>内容。</p>',
];const keywords = ["测试", "GVM"];
function highlightKeyword(inputContent, keyword) {if (!keyword) return inputContent; // 如果没有关键字,直接返回原始内容// 转义用户输入的关键字,避免正则表达式特殊字符冲突const escapeRegExp = (str) =>str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");// 创建匹配关键字的正则表达式const keywordRegex = new RegExp(`(${escapeRegExp(keyword)})`, "gi");// 判断是否为普通文本(没有 HTML 标签)const isPlainText = !/<[^>]+>/.test(inputContent);if (isPlainText) {// 普通文本处理return inputContent.replace(keywordRegex,'<span class="highlight">$1</span>');}// HTML 内容处理const parser = new DOMParser();const doc = parser.parseFromString(inputContent, "text/html");// 遍历节点,处理文本高亮function traverseNodes(node) {if (node.nodeType === Node.TEXT_NODE) {// 替换关键字为高亮的内容const parent = node.parentNode;const highlightedHTML = node.textContent.replace(keywordRegex,'<span class="highlight">$1</span>');// 用安全的 HTML 替换if (highlightedHTML !== node.textContent) {const temp = document.createElement("div");temp.innerHTML = highlightedHTML;while (temp.firstChild) {parent.insertBefore(temp.firstChild, node);}parent.removeChild(node);}} else if (node.nodeType === Node.ELEMENT_NODE) {// 递归处理子节点Array.from(node.childNodes).forEach(traverseNodes);}}traverseNodes(doc.body);// 返回处理后的 HTMLreturn doc.body.innerHTML;
}