javascript / jQuery - 在不替换整个正文的情况下替换正文中出现的所有字符串的最有效方法是什么

javascript / jQuery - What is the most efficiënt way to replace all the occurrences of a string in a body without replacing the entire body

我想替换网页正文中出现的所有特定字符串而不替换整个正文(因为它可能会破坏事件监听器等)。有没有办法做到这一点,如果有,最好的方法是什么?

举个例子:

我们有以下代码:

<body>
    <div class="header">
        #parameter#
    </div>
    <div class="body">
        <div class="some-widget">
            we have some code here
            <div class="text">
                And also our #parameter#
            </div>
        </div>
    </div>
</body>

如前所述,我们可以使用类似

的东西
$('body').html($('body').html().replace(/#parameter#/g, 'Our parameter value'));

但这可能会使我们的 some-widget 变得无用。

我们不知道网页在结构上会是什么样子,所以我们无法寻找 #parameter#

的某些容器

理想情况下,我认为我们将对“#parameter#”执行搜索,获取父元素,然后按上述方式替换父元素html。但是,我不知道这是否可行以及如何实现。我得到的最接近的是 ,但它并没有让我走得更远。

谢谢!

您可以 iterate over all text nodes 并替换他们的 nodeValue:

function getTextNodes(parent) {
    const walker = document.createTreeWalker(
        parent,
        NodeFilter.SHOW_TEXT,
        null,
        false
    );

    let node;
    const nodes = [];

    while(node = walker.nextNode()) {
        nodes.push(node);
    }
    return nodes;
}

for (const node of getTextNodes(document.body)) {
  node.nodeValue = node.nodeValue.replaceAll('#parameter#', 'foo');
}
<body>
    <div class="header">
        #parameter#
    </div>
    <div class="body">
        <div class="some-widget">
            we have some code here
            <div class="text">
                And also our #parameter#
            </div>
        </div>
    </div>
</body>