One
One

Reputation: 43

How to replace word with javascript?

In some forum I join, they just replace some link with something like spam or deleted. Example: www.rapidshare.com/download/123 will automatically turn to www.spam.com/download/123 OR word MONEY will change to BOSS.

Its really annoyed me because I have to rename back manually if I want to download. Is there any Javascript that can solve this that will replace back www.spam.com to www.rapidshare.com? I mean in client side.

Thanks

Upvotes: 3

Views: 423

Answers (2)

alex
alex

Reputation: 490497

If these URLs are in href attributes...

var replaceHrefAttributes = function (element, search, replace) {
    var nodes = element.getElementsByTagName('a');

    for (var i = 0, length = nodes.length; i < length; i++) {

        var node = nodes[i];

        if (node.href == undefined) {
            continue;
        }

        node.href = node.href.replace(new RegExp(search, 'g'), replace);
    }

}

Your usage may be something like...

replaceHrefAttributes(document.body, 'www.spam.com', 'www.rapidshare.com');

If these URLs are inline text...

You could iterate over all text nodes, using replace() to replace any string with another.

Here is a general purpose recursive function I've written to do this...

var replaceText = function replaceText(element, search, replace) {
    var nodes = element.childNodes;

    for (var i = 0, length = nodes.length; i < length; i++) {

        var node = nodes[i];

        if (node.childNodes.length) {
            replaceText(node, search, replace);
            continue;
        }

        if (node.nodeType != 3) {
            continue;
        }

        node.data = node.data.replace(new RegExp(search, 'g'), replace);
    }

}

Your usage may be something like...

replaceText(document.body, 'www.spam.com', 'www.rapidshare.com');

If you are curious as to how the code works, here is a brief explanation...

  1. Get all child nodes of the element. This will get text nodes and elements.
  2. Iterate over all of them.
  3. If this node has child nodes of its own, call the function again with element as the element in the loop. continue because we can't modify this as it is not a text node.
  4. If this node's nodeType property is not 3 (i.e. a text node), then continue as again we can't modify any text.
  5. We are confident this is a text node now, so replace the text.

You could make this function more flexible by passing search straight to it, allowing it to search for text using a string or a regular expression.

Upvotes: 3

viclm
viclm

Reputation: 203

var a = document.getElementsByTagName('a');
for (var i = 0, len = a.length ; i < len ; i += 1) {
    a.firstChild.nodeValue = a.href;
}

Upvotes: 0

Related Questions