[英]Replace all words in html without affecting tags
I am looking for a way to replace all instances of Foo
with <a>Bar</a>
(a functioning link) in a given website.我正在寻找一种方法来将给定网站中的所有
Foo
实例替换为<a>Bar</a>
(一个功能链接)。 Ideally without any extra library like jquery.理想情况下没有任何额外的库,如 jquery。
What I tried:我试过的:
document.body.innerHtml
and similars ( document.getElementByTagName('p)
) won't work with a simple .replace(/Foo/g, '<a>Bar</a>')
because it may end up replacing a Foo
class-name or id, so it breaks the page. document.body.innerHtml
和类似的document.getElementByTagName('p)
( document.getElementByTagName('p)
)不适用于简单的.replace(/Foo/g, '<a>Bar</a>')
因为它最终可能会替换一个Foo
类名或 id,所以它打破了页面。 Also may affect some js scripts in the body.a
tags as text, instead of creating DOM elements.a
,而不是创建DOM元素的标签为文本。.replace
there just generates the same problem as the first bullet..replace
只会产生与第一个项目符号相同的问题。 I've searched for answers to other similar questions but I haven't found any that solves this three points.我已经搜索了其他类似问题的答案,但没有找到解决这三点的答案。
You're close, but you need to replace the entire text node with a set of three new nodes:你已经接近了,但你需要用一组三个新节点替换整个文本节点:
<a>
unless it's an actual link), and then<a>
除非它是一个实际的链接),然后 And then, of course, that remaining textnode is now part of the still-unprocessed set of text nodes.然后,当然,剩余的文本节点现在是尚未处理的文本节点集的一部分。
(unless you do a split
for your term, then interleave as many additional nodes as needed. Then you just run through textnodes one by one without having to put "the remainder" back on your stack) (除非你对你的任期进行
split
,然后根据需要交错尽可能多的额外节点。然后你只需一个一个地运行文本节点,而不必将“剩余部分”放回堆栈中)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.