Javascript 替换正文中的单词

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5558613/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:48:14  来源:igfitidea点击:

Replace words in the body text

javascripthtml

提问by Wahtever

Is there a way to replace the normal text within a table element that is placed within the body of the HTML?

有没有办法替换放置在 HTML 正文中的表格元素中的普通文本?

Like replacing "hello" with "hi"?

喜欢用“嗨”代替“你好”?

Please only use JavaScriptwithout jQuery.

请只使用没有jQuery 的JavaScript

回答by Dexter

To replace a string in your HTML with another use the replacemethod on innerHTML:

要将 HTML 中的字符串替换为另一个字符串,请使用innerHTML上的replace方法:

document.body.innerHTML = document.body.innerHTML.replace('hello', 'hi');

Note that this will replace the first instance of hellothroughout the body, including any instances in your HTML code (e.g. class names etc..), so use with caution - for better results, try restricting the scope of your replacement by targeting your code using document.getElementByIdor similar.

请注意,这将替换hello整个正文中的第一个实例,包括 HTML 代码中的任何实例(例如类名等),因此请谨慎使用 - 为了获得更好的结果,请尝试通过使用以下代码来限制替换范围document.getElementById或类似的。

To replace all instances of the target string, use a simple regular expression with the global flag:

要替换目标字符串的所有实例,请使用带有global 标志的简单正则表达式:

document.body.innerHTML = document.body.innerHTML.replace(/hello/g, 'hi');

回答by Ziad

The function below works perfectly for me:

下面的功能非常适合我:

// Note this *is* JQuery, see below for JS solution instead
function replaceText(selector, text, newText, flags) {
  var matcher = new RegExp(text, flags);
  $(selector).each(function () {
    var $this = $(this);
    if (!$this.children().length)
       $this.text($this.text().replace(matcher, newText));
  });
}

Here's a usage example:

这是一个使用示例:

function replaceAllText() {
  replaceText('*', 'hello', 'hi', 'g');
}

$(document).ready(replaceAllText);
$('html').ajaxStop(replaceAllText);

You can also use do a direct replacement like so:

您还可以使用 do 直接替换,如下所示:

document.body.innerHTML = document.body.innerHTML.replace('hello', 'hi');

But be careful with it since it may affect the tags, css and scripts as well.

但要小心,因为它也可能影响标签、css 和脚本。

EDIT:As for a pure JavaScript solution use this method instead:

编辑:对于纯 JavaScript 解决方案,请改用此方法:

function replaceText(selector, text, newText, flags) {
  var matcher = new RegExp(text, flags);
  var elems = document.querySelectorAll(selector), i;

  for (i = 0; i < elems.length; i++)
    if (!elems[i].childNodes.length)
      elems[i].innerHTML = elems[i].innerHTML.replace(matcher, newText);
}

回答by funky-future

I ended up with this function to safely replace text without side effects (so far):

我最终用这个函数来安全地替换文本而没有副作用(到目前为止):

function replaceInText(element, pattern, replacement) {
    for (let node of element.childNodes) {
        switch (node.nodeType) {
            case Node.ELEMENT_NODE:
                replaceInText(node, pattern, replacement);
                break;
            case Node.TEXT_NODE:
                node.textContent = node.textContent.replace(pattern, replacement);
                break;
            case Node.DOCUMENT_NODE:
                replaceInText(node, pattern, replacement);
        }
    }
}

It's for cases where the 16kB of findAndReplaceDOMTextare a bit too heavy.

它适用于 16kBfindAndReplaceDOMText有点太重的情况。

回答by David Silva Smith

I had the same problem. I wrote my own function using replace on innerHTML, but it would screw up anchor links and such.

我有同样的问题。我在innerHTML 上使用replace 编写了我自己的函数,但它会搞砸锚链接等。

To make it work correctly I used a libraryto get this done.

为了使其正常工作,我使用了一个来完成这项工作。

The library has an awesome API. After including the script I called it like this:

该库有一个很棒的 AP​​I。包含脚本后,我这样称呼它:

findAndReplaceDOMText(document.body, {
  find: 'texttofind',
  replace: 'texttoreplace'
  }
);

回答by Mark Costello

Use the default javascript string replace function

使用默认的javascript字符串替换功能

var curInnerHTML = document.body.innerHTML;
curInnerHTML = curInnerHTML.replace("hello", "hi");
document.body.innerHTML = curInnerHTML;

回答by Bartho Bernsmann

I was trying to replace a really large string and for some reason regular expressions were throwing some errors/exceptions.

我试图替换一个非常大的字符串,但由于某种原因,正则表达式抛出了一些错误/异常。

So I found this alternative to regular expressions which also runs pretty fast. At least it was fast enough for me:

所以我找到了这个正则表达式的替代品,它也运行得非常快。至少对我来说已经足够快了:

var search = "search string";
var replacement = "replacement string";

document.body.innerHTML = document.body.innerHTML.split(search).join(replacement)

src: How to replace all occurrences of a string in JavaScript?

src:如何替换 JavaScript 中所有出现的字符串?

回答by FentomX1

Try to apply the above suggested solution on pretty big document, replacing pretty short strings which might be present in innerHTML or even innerText, and your html design becomes broken at best

尝试将上述建议的解决方案应用于相当大的文档,替换可能存在于innerHTML 甚至innerText 中的相当短的字符串,并且您的html 设计充其量会损坏

Therefore I firstly pickup only text node elements via HTML DOM nodes, like this

因此,我首先通过 HTML DOM 节点仅拾取文本节点元素,如下所示

function textNodesUnder(node){
  var all = [];
  for (node=node.firstChild;node;node=node.nextSibling){
    if (node.nodeType==3) all.push(node);
    else all = all.concat(textNodesUnder(node));
  }
  return all;
}

textNodes=textNodesUnder(document.body)
for (i in textNodes) { textNodes[i].nodeValue = textNodes[i].nodeValue.replace(/hello/g, 'hi');    

`and followingly I applied the replacement on all of them in cycle

`然后我在循环中对所有它们应用了替换

回答by Y Stroli

Wanted to add an example to funky-future's answeras I kept getting this error:

想在funky-future 的答案中添加一个示例,因为我不断收到此错误:

Uncaught TypeError: element.childNodes is not iterable

use like this:

像这样使用:

replaceInText(document.body,"search term","replacement");

it didn't work for me with jQuery selectors.

它不适用于 jQuery 选择器。

回答by Manish

I am new to Javascriptand just started learning these skills. Please check if the below method is useful to replace the text.

我是新手Javascript,刚刚开始学习这些技能。请检查以下方法是否对替换文本有用。

<script>

    var txt=document.getElementById("demo").innerHTML;
    var pos = txt.replace(/Hello/g, "hi")
    document.getElementById("demo").innerHTML = pos;

</script>