替换正文文本中的单词

时间:2022-09-13 09:44:24

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"?

比如用“hi”代替“hello”?

Please only use JavaScript without jQuery.

请在没有jQuery的情况下使用JavaScript。

8 个解决方案

#1


93  

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

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

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

Note that this will replace the first instance of hello throughout 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.getElementById or similar.

注意,这将替换整个主体中的第一个hello实例,包括HTML代码中的任何实例(例如类名等),所以要小心使用——为了获得更好的结果,尝试通过使用文档锁定代码来限制替换的范围。getElementById或类似。

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

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

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

#2


11  

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);
}

#3


6  

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 library to get this done.

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

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

这个库有一个很棒的API。在包括这个脚本之后,我这样称呼它:

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

#4


2  

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?

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

#5


0  

Use the default javascript string replace function

使用默认的javascript字符串替换函数

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

#6


0  

I am new to Javascript and 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>

#7


0  

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

接着,我把替换物按循环应用到所有的设备上

#8


0  

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 findAndReplaceDOMText are a bit too heavy.

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

#1


93  

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

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

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

Note that this will replace the first instance of hello throughout 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.getElementById or similar.

注意,这将替换整个主体中的第一个hello实例,包括HTML代码中的任何实例(例如类名等),所以要小心使用——为了获得更好的结果,尝试通过使用文档锁定代码来限制替换的范围。getElementById或类似。

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

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

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

#2


11  

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);
}

#3


6  

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 library to get this done.

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

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

这个库有一个很棒的API。在包括这个脚本之后,我这样称呼它:

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

#4


2  

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?

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

#5


0  

Use the default javascript string replace function

使用默认的javascript字符串替换函数

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

#6


0  

I am new to Javascript and 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>

#7


0  

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

接着,我把替换物按循环应用到所有的设备上

#8


0  

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 findAndReplaceDOMText are a bit too heavy.

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