Skip to content

Instantly share code, notes, and snippets.

@shuhei
Last active November 21, 2020 11:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shuhei/d3111dcaadc1bc28c401adad9758609c to your computer and use it in GitHub Desktop.
Save shuhei/d3111dcaadc1bc28c401adad9758609c to your computer and use it in GitHub Desktop.
Replacing text in a document
// Recursive
function replaceText(node, from, to) {
switch (node.nodeType) {
case Node.TEXT_NODE:
node.textContent = node.textContent.replace(from, to);
break;
case Node.ELEMENT_NODE:
for (const childNode of node.childNodes) {
replaceText(childNode, from, to);
}
break;
default:
// Ignore comment, etc.
}
}
// Or NodeIterator!
function replaceText(root, from, to) {
const itr = document.createNodeIterator(root, NodeFilter.SHOW_TEXT);
let node;
while (node = itr.nextNode()) {
node.textContent = node.textContent.replace(from, to);
}
}
// Example
replaceText(document.body, / +/g, " 🎄 ");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment