如何在javascript中多次替换相同的单词?

时间:2017-04-05 19:48:55

标签: javascript replace

我们的开发者在整个网站上使用了此电话号码1-866-579-469,但正确的电话号码为1-866-579-4269。我编写了一个javascript函数来替换所有出现的内容:

var nodes,currentElement,oldtext,newtext,replaced,count;
function replaceAll(nodes,oldtext,newtext,replaced) { 
    count = 0
  for (var i = 0; i < nodes.length; i++) {
    currentElement  = nodes[i].innerHTML;  
    replaced = currentElement.replace(oldtext,newtext);
    count++;
  }
  console.log("Edited: "+ count + " items");
}

oldtext = "1-866-579-469";
newtext = "1-866-579-4269";
nodes = document.getElementsByTagName('*');

replaceAll(nodes,oldtext,newtext,replaced);

1 个答案:

答案 0 :(得分:1)

您的代码有效,但您错过了更新替换后的字符串。这应该有效:

var nodes,currentElement,oldtext,newtext,replaced,count;
function replaceAll(nodes,oldtext,newtext,replaced) { 
    count = 0
  for (var i = 0; i < nodes.length; i++) {
    currentElement  = nodes[i].innerHTML;  
    replaced = currentElement.replace(oldtext,newtext);
    nodes[i].innerHTML = replaced;
    count++;
  }
  console.log("Edited: "+ count + " items");
}

oldtext = "1-866-579-469";
newtext = "1-866-579-4269";
nodes = document.getElementsByTagName('*');

replaceAll(nodes,oldtext,newtext,replaced);

Codepen Here