Skip to content

Instantly share code, notes, and snippets.

@shuhei
Last active Nov 21, 2020
Embed
What would you like to do?
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