繁体   English   中英

如何使用javascript(而不是标签或属性)替换字符串中所有匹配的纯文本字符串?

[英]how to replace all matching plain text strings in string using javascript (but not tags or attributes)?

想象一下页面上的这个html

<div id="hpl_content_wrap">
<p class="foobar">this is one word and then another word comes in foobar and then more words and then foobar again.</p>
<p>this is a <a href="http://foobar.com" data-bitly-type="bitly_hover_card">link with foobar in an attribute</a> but only the foobar inside of the link should be replaced.</p>
</div>

使用javascript,如何将所有“ foobar”字词更改为“ herpderp”而不更改html标签内部?

即。 仅纯文本应更改。

因此成功的html更改将是

<div id="hpl_content_wrap">
<p class="foobar">this is one word and then another word comes in herpderp and then more words and then herpderp again.</p>
<p>this is a <a href="http://foobar.com" data-bitly-type="bitly_hover_card">link with herpderp in an attribute</a> but only the herpderp inside of the link should be replaced.    </p>
</div>

这是您需要做的...

  1. 获取对一堆元素的引用。
  2. 递归地遍历子级,仅替换文本节点中的文本。

很抱歉造成延迟,在添加代码之前,我被束缚了。

var replaceText = function me(parentNode, find, replace) {
    var children = parentNode.childNodes;

    for (var i = 0, length = children.length; i < length; i++) {
        if (children[i].nodeType == 1) {
            me(children[i], find, replace);            
        } else if (children[i].nodeType == 3) {
            children[i].data = children[i].data.replace(find, replace);
        }

    }

    return parentNode;

}

replaceText(document.body, /foobar/g, "herpderp");​​​

jsFiddle

这很简单:

  • 识别DOM树中的所有文本节点,
  • 然后替换其中的所有foobar字符串。

这是完整的代码:

// from: https://stackoverflow.com/questions/298750/how-do-i-select-text-nodes-with-jquery
var getTextNodesIn = function (el) {
    return $(el).find(":not(iframe)").andSelf().contents().filter(function() {
        return this.nodeType == 3;
    });
};

var replaceAllText = function (pattern, replacement, root) {
    var nodes = getTextNodesIn(root || $('body'))
    var re    = new RegExp(pattern, 'g')

    nodes.each(function (i, e) {
        if (e.textContent && e.textContent.indexOf(pattern) != -1) {
           e.textContent = e.textContent.replace(re, replacement);
        }
    });
};


// replace all text nodes in document's body
replaceAllText('foobar', 'herpderp');

// replace all text nodes under element with ID 'someRootElement'
replaceAllText('foobar', 'herpderp', $('#someRootElement'));

请注意,我对foobar进行了预检查,以避免使用正则表达式处理疯狂的长字符串。 可能是一个好主意。

如果您不想使用jQuery,而只希望使用纯JavaScript,请遵循代码段中的链接( 如何使用jQuery选择文本节点? ),您还将在其中找到仅JS版本来获取节点。 然后,您只需以类似的方式遍历返回的元素。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM