Reputation: 43
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
Reputation: 490497
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');
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...
element
. This will get text nodes and elements.element
as the element
in the loop. continue
because we can't modify this as it is not a text node.nodeType
property is not 3
(i.e. a text node), then continue
as again we can't modify any 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
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