如何在HTML DOM中进行多次替换?

时间:2017-06-19 03:59:37

标签: javascript dom replace

我有用于替换HTML中的文字链接的JavaScript代码,但该代码仅适用于单个替换。我需要更换许多文字&我的HTML代码中的链接

var search = "Selena";
var replacement = "Love";

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

3 个答案:

答案 0 :(得分:1)

通过一些准备工作,您可以使用TreeWalker来完成此操作而无需有效地覆盖整个DOM - 这很慢,并且您丢失了添加到元素的任何事件侦听器



var replacements = {
    'Selena': 'Love',
    'mical': 'jhon',
    'sara': 'nida',
    'jhoony': 'joona'
};
var keys = Object.keys(replacements);
var regex = new RegExp(keys.join('|'),'g');
var replacer = function(str) {
    return str.replace(regex, function (key) {
        return replacements[key];
    });
}
    
var treeWalker = document.createTreeWalker(
    document.body,
    NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT, { 
        acceptNode: function(node) {
            // only processing non-empty text nodes, and <A> with non empty href
            if ((node.nodeName == '#text' && node.nodeValue) || (node.nodeName == 'A' && node.href)) {
                return NodeFilter.FILTER_ACCEPT; 
            }
            // Skip this node, but still consider its child nodes
            return NodeFilter.FILTER_SKIP;
        } 
    },
    false
);

while(treeWalker.nextNode()) {
    var node = treeWalker.currentNode;
    var replace;
    if (node.nodeName == '#text') {
        node.nodeValue = replacer(node.nodeValue);
    } else {
        node.href = replacer(node.href);
    }
}
&#13;
<span>Selena
    <b>mical</b>
    sara
    <a href='#jhoony'>Link to #jhoony</a>
</span>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以使用g(全局)标记的regex替换所有发生的标记。 如果你想不区分大小写在正则表达式中使用i标志:

  var search = ["Selena", "jhon sara"];
  var replacement = ["Love", "nida"] ;
  var html = document.body.innerHTML;

  for(var i =0; i<search.length; i++) {
    var search_regex = new RegExp(search[i],"gi");

    html = html.replace(search_regex, replacement[i]);
  }

  document.body.innerHTML = html;
Selena is selena. Jhon sara is jhon sara.

答案 2 :(得分:-1)

尝试使用Regex。

document.body.innerHTML = document.body.innerHTML.replace(/Selena/g,"Love")

来源:https://www.w3schools.com/jsref/jsref_obj_regexp.asp