javascript - 对元素中的所有文本应用正则表达式

标签 javascript html regex replace

我正在尝试使用 JS 将特定单词动态替换为某个 HTML 元素中的链接。我想我会使用一个简单的正则表达式:

var regEx = new RegExp('\\b'+text+'\\b', 'gi');

在上下文 div 的 innerHTML 属性上应用 RegEx 替换的快速'n'nasty 方法:

context.innerHTML = context.innerHTML.replace(regEx, '<a href="#">'+text+"</a>");

问题在于它也适用于图像标题,从而破坏了页面布局。我希望它只应用于页面的文本,如果可能的话还排除诸如标题标签之类的内容,当然还有 HTML 注释等。

所以我尝试了类似的方法,但它似乎根本不起作用:

function replaceText(context, regEx, replace) {
    var childNodes = context.childNodes;
    for (n in childNodes) {
        console.log(childNodes[n].nodeName);
        if (childNodes[n] instanceof Text) {
            childNodes[n].textContent = childNodes[n].textContent.replace(regEx, replace);
        } else if (childNodes[n] instanceof HTMLElement) {
            replaceText(childNodes[n], regEx, replace);
            console.log('Entering '+childNodes[n].nodeName);
        } else {
            console.log('Skipping '+childNodes[n].nodeName);
        }
    }
}

谁能看出我做错了什么,或者想出更好的解决方案?谢谢!

更新:

下面是 context 内容的片段:

<h4>Newton's Laws of Motion</h4>
<p><span class="inline_title">Law No.1</span>: <span class="caption">An object at rest will remain at rest, and an object in motion will continue to move at constant velocity, unless a net force is applied.</span></p>
<ul>Consequences: <li>Conservation of Momentum in both elastic and inelastic collisions</li>
<li>Conservation of kinetic energy in elastic collisions but not inelastic.</li>
<li>Conservation of angular momentum.</li>
</ul>
<h5>Equations</h5>
<p class="equation">&rho; = mv</p>
<p>where &rho; is the momentum, and m is the mass of an object moving at constant velocity v.</p>

最佳答案

你可以使用这个:

function replaceText(context, regEx, replace)
{
    var childNodes = context.childNodes;
    for (var i = 0; i<childNodes.length; i++) {
        var childNode = childNodes[i];
        if (childNode.nodeType === 3) // 3 is for text node
            childNode.nodeValue = childNode.nodeValue.replace(regEx, replace);
        else if (childNode.nodeType === 1 && childNode.nodeName != "HEAD")
            replaceText(childNode, regEx, replace); 
    }
}
replaceText(context, /cons/ig, 'GROUIK!');

想法是在“上下文”DOM 树中找到所有文本节点,这就是我使用递归函数在子节点内搜索文本节点的原因。

注意:我在函数中测试了childNode.nodeName != "HEAD"。这只是避免特定标签的示例。在现实生活中,将 body 节点作为函数的参数更为简单。

关于javascript - 对元素中的所有文本应用正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20730130/

相关文章:

javascript - 无法在 JavaScript Windows 应用程序中注册后台任务

javascript - jQuery 按钮样式仅应用于 Datatable 第一页中的按钮

javascript - 如何在避免闪烁的同时平移元素?

regex - 正则表达式长度 (0) 或 (7-50)

javascript - 从链接中获取字段值

javascript - 将带有随机数的 CSP header 添加到 Lambda Edge

javascript - ngModel 反射(reflect)到所有文本区域

html - 均匀分开的 DIV 技术不起作用

regex - 统计词频然后排序

Python 正则表达式 : using or statement