【发布时间】:2021-11-11 09:33:54
【问题描述】:
我正在尝试遍历所有 nodes 并检查该节点是否包含 terms 数组中的任何项目并将这些单词包装到 span 标签中。
function getAllTextNodes(element) {
let node;
let nodes = [];
let walk = document.createTreeWalker(element,NodeFilter.SHOW_TEXT,null,false);
while (node = walk.nextNode()) nodes.push(node);
return nodes;
}
const editor = document.getElementById('editor');
const allNodes = getAllTextNodes(editor);
const terms = [
{
"id": 1,
"definition": "A knowledge base is a published collection of documentation that typically includes answers to frequently asked questions, how-to guides, and troubleshooting",
"expression": "knowledge base",
},
{
"id": 2,
"definition": "Knowledge management (KM) is the process of creating, sharing, using and managing the knowledge and information of an organization",
"expression": "knowledge management",
},
{
"id": 3,
"definition": "this is test",
"expression": "base",
},
{
"id": 4,
"definition": "management glossary item test",
"expression": "management",
},
{
"id": 5,
"definition": "test",
"expression": "Knowledge",
}
]
allNodes.forEach(node => {
if (node.parentNode !== null) {
// Create New Node
let newNode = document.createElement('p');
newNode.innerHTML = node.parentNode.innerHTML;
for (const term of terms) {
if (node.textContent.toLowerCase().includes(term.expression.toLowerCase())) {
const termNames = newNode.textContent.match(new RegExp("\\b" + term.expression + "\\b", "ig"))
if (termNames !== null) {
termNames.forEach((name, index) => {
newNode.innerHTML = newNode.innerHTML.replace(newNode.textContent.match(new RegExp("\\b" + term.expression + "\\b", "ig"))[index], `<span class='hj-glossary-item' data-definition='${term.definition}' data-id='${term.id}'>${name}</span>`)
})
}
}
}
// Update Node
node.parentNode.innerHTML = newNode.innerHTML;
}
})
<div id="editor">
<p>Management is the reason why knowledge management is important. Knowledge base is also important to base.</p>
<p>Management is the reason why knowledge management is important. Knowledge base is also important to base.</p>
<p>Management is the reason why knowledge management is important. Knowledge base is also important to base.</p>
</div>
【问题讨论】:
标签: javascript arrays regex