Skip to content

Instantly share code, notes, and snippets.

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 cpuuntery/2e772902a84ad6ab94e9d7acdc198b6d to your computer and use it in GitHub Desktop.
Save cpuuntery/2e772902a84ad6ab94e9d7acdc198b6d to your computer and use it in GitHub Desktop.
const replaceOnDocument = (pattern, string, {target = document.body} = {}) => {
[target,...target.querySelectorAll("*:not(script):not(noscript):not(style)")]
.forEach(({childNodes: [...nodes]}) => nodes
.filter(({nodeType}) => nodeType === document.TEXT_NODE)
.forEach((textNode) => textNode.textContent = textNode.textContent.replace(pattern, string)));
};
replaceOnDocument(/€/g, "$");
function replaceRecursively(element, from, to) {
if (element.childNodes.length) {
element.childNodes.forEach(child => replaceRecursively(child, from, to));
} else {
const cont = element.textContent;
if (cont) element.textContent = cont.replace(from, to);
}
};
replaceRecursively(document.body, new RegExp("hello", "g"), "hi");
var treeWalker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
while(treeWalker.nextNode()) {
var node = treeWalker.currentNode;
node.nodeValue = node.nodeValue.replace(/e/g, '∑');
}
#jquery is required
$(document.body).find("*").contents().filter(function() {return this.nodeType === 3}).each(function() {this.nodeValue = this.nodeValue.replace(/foo/g, "bar")});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment