Skip to content Skip to sidebar Skip to footer

Javascript: How Do I Change Every Word Visible On Screen?

I want to do a joke code that changes every word on screen by an specific other word, for example: 'I like trains' --> 'hello hello hello' Well, that's easy. The problem is to s

Solution 1:

Recursively walk the nodes and do a regex replace. Quick and dirty example:

function replaceAllWords(newWord) {
    for (var i = 0; i < 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) {
            for (var j = 0; j < node.childNodes.length; j++) {
                checkNode(node.childNodes[j]);
            }
        }
    }
}

//Use like
replaceAllWords("Hello");

Doing a regex on innerHtml will replace anything that matches, including any block script thats on the page. This function checks that it is actually a text node, before doing a replace, the replace only does word characters (A-Za-z0-9_) that are 1 or more characters, so will not replace spaces or symbols (i.e. punctuation, $ etc will stay put)


Solution 2:

You mean something like this?

var old = $('body').html();
$('body').html(old.replace('I like trains', 'hello hello'));

With Pure JS:

var new = document.getElementsByTagName('body')[0].innerHTML.replace('I like trains','bye');
 document.getElementsByTagName('body')[0].innerHTML= new;

Post a Comment for "Javascript: How Do I Change Every Word Visible On Screen?"