JSFiddle - React, Tailwind, and code Playground

by Graham Fairweather

HTML

<div>
    <p>Superman and some other text</p>
</div>
<div>
    <p>More Superman and some other text</p>
</div>
<div>
    <p>Something Supermanish and some other text</p>
</div>

JavaScript

function walkTheDOM(node, func) {
    func(node);
    node = node.firstChild;
    while (node) {
        walkTheDOM(node, func);
        node = node.nextSibling;
    }
}

function escapeRegex(string) {
    return string.replace(/[\[\](){}?*+\^$\\.|]/g, "\\$&");
}

function replaceText(node, searchText, replaceText) {
    var textNodes = [],
        length,
        i;

    function filterTextNodes(currentNode) {
        if (currentNode.nodeType === 3) {
            textNodes.push(currentNode);
        }
    }

    walkTheDOM(node, filterTextNodes);

    i = 0;
    length = textNodes.length;
    while (searchText && i < length) {
        textNodes[i].nodeValue = textNodes[i].nodeValue.replace(new RegExp("\\b" + escapeRegex(searchText) + "\\b"), replaceText);
        i += 1;
    }
}

var query = {
    alt_name: "Giggitty",
    test: "brand",
    old: "Superman",
    new: "Batman"
};

if (query.test === "brand") {
    replaceText(document, query.old, query.new);
}