Javascript: How do I change every word visible on screen? -
i want joke code changes every word on screen specific other word, example: "i trains" --> "hello hello hello" well, that's easy. problem select every text on screen. can me?
recursively walk nodes , regex replace. quick , dirty example:
function replaceallwords(newword) { (var = 0; < document.childnodes.length; i++) { checknode(document.childnodes[i]); } function checknode(node) { var nodename = node.nodename.tolowercase(); if(nodename === 'script' || nodename === 'style') {return;} if (node.nodetype === 3) { var text = node.nodevalue; var newtext = text.replace(/\b\w+/g, newword); node.nodevalue = newtext; } if (node.childnodes.length > 0) { (var j = 0; j < node.childnodes.length; j++) { checknode(node.childnodes[j]); } } } } //use replaceallwords("hello");
doing regex on innerhtml replace matches, including block script thats on page. function checks text node, before doing replace, replace word characters (a-za-z0-9_) 1 or more characters, not replace spaces or symbols (i.e. punctuation, $ etc stay put)
Comments
Post a Comment