使用Javascript将特定文本(基于模式识别)转换为链接
下面的代码是基于模式在DOM中查找特定文本。 与其替换文本,我想将其转换为链接,其中文本是链接中的参数 假设链接看起来像: 我想将其转换为链接,而不是替换文本 因此,与其替换文本,不如:使用Javascript将特定文本(基于模式识别)转换为链接,javascript,Javascript,下面的代码是基于模式在DOM中查找特定文本。 与其替换文本,我想将其转换为链接,其中文本是链接中的参数 假设链接看起来像: 我想将其转换为链接,而不是替换文本 因此,与其替换文本,不如: 创建链接 让newLink=document.createElement('a')) 配置链接 newLink.href=”https://google.com/search?q='+encodeURIComponent(节点值) newLink.textContent=nodeValue 将文本节点替换为
让newLink=document.createElement('a'))
newLink.href=”https://google.com/search?q='+encodeURIComponent(节点值)
newLink.textContent=nodeValue
tmpnode.replaceWith(newLink)
我想将其转换为链接,而不是替换文本
因此,与其替换文本,不如:
让newLink=document.createElement('a'))
newLink.href=”https://google.com/search?q='+encodeURIComponent(节点值)
newLink.textContent=nodeValue
tmpnode.replaceWith(newLink)
var allTextNodes = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT),
// some temp references for performance
tmptxt,
tmpnode,
// compile the RE and cache the replace string, for performance
identify = /ABC\d{7}/g,
replaceValue = "changed";
// iterate through all text nodes
while (allTextNodes.nextNode()) {
tmpnode = allTextNodes.currentNode;
tmptxt = tmpnode.nodeValue;
tmpnode.nodeValue = tmptxt.replace(identify, replaceValue);
}