Search code examples
javascriptgreasemonkeyuserscripts

How do I replace every word with one word?


I would like Javascript which changes all text on a page to a specific string. For example, if I wanted to set every word to 'Hello':

Before:

Hey there, how are you?

After:

Hello Hello Hello Hello Hello

How would this be done? It would do it to the entire page, so it would need to leave HTML tags as they were and just change the text contents.

This code must be executed after the page has loaded.


Solution

  • function malkovich(node) {
      if(node.nodeType === 1)
        return [].forEach.call(node.childNodes, malkovich);
      if(node.nodeType === 3)  
        node.textContent = node.textContent
             .replace(/\b[A-Z]\w+/g, "Malkovich")
             .replace(/\b[a-z]\w+/g, "malkovich")
    }
    <h1>Hi, there!</h1>
    <p>Some <b>more</b> text...</p>
    <p>"Gallia est omnis divisa in partes tres, quarum <u>unam</u> incolunt <i>Belgae</i>, <u>aliam</u> <i>Aquitani</i>, <u>tertiam</u> qui ipsorum lingua <i>Celtae</i>, nostra <i>Galli</i> appellantur". </p>
    <button onclick="malkovich(document.body)">malkovich</button>