1

Our developer used this phone number 1-866-579-469 all over the website but the correct phone number is 1-866-579-4269. I have written a javascript function to replace all occurrences:

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);
4
  • if counting items is not critical, the replacement can be done in a much shorter way Commented Apr 5, 2017 at 19:53
  • Can you please tell me that way? Commented Apr 5, 2017 at 19:58
  • I could post an answer, but you already had one Commented Apr 5, 2017 at 20:01
  • what is the shorter way? Commented Apr 5, 2017 at 20:03

1 Answer 1

1

Your code works but you missed to update the replaced string. This should work:

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.