gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 09:51:08 26 4
gpt4 key购买 nike

想象一下页面上的这个 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 .

关于javascript - 如何使用javascript替换字符串中所有匹配的纯文本字符串(但不是标签或属性)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10943166/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com