Last active
November 21, 2020 11:23
-
-
Save shuhei/d3111dcaadc1bc28c401adad9758609c to your computer and use it in GitHub Desktop.
Replacing text in a document
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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