0

I am parsing the following query string:

/?alt_name=test&test=brand&old=Superman&new=Batman

and get this Object {alt_name: "Giggitty", test: "brand", old: "Supco", new: "Batman"}.

How would I go about creating a script that if the test=brand replace inner html instances of the word Superman(old) with the word Batman(new)?

Any help is greatly appriciated.

Edit. HTML would help although a super simple example will suffice.

<html>
    <body>
        <div>
            <p>Superman and some other text</p>
        </div>
    </body>
</html>

Basically I just want every instance of the word Superman, or whatever the parsed value for old, to be replaced with whatever the parsed value for new is, in this case Batman.

Taryn
  • 242,637
  • 56
  • 362
  • 405

1 Answers1

0

You could do something like this if you want to match exactly "Superman" and not something that contains it.

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);
}

On jsfiddle

Xotic750
  • 22,914
  • 8
  • 57
  • 79