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
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...
- Get all child nodes of the
element
. This will get text nodes and elements. - Iterate over all of them.
- If this node has child nodes of its own, call the function again with
element
as theelement
in the loop.continue
because we can't modify this as it is not a text node. - If this node's
nodeType
property is not3
(i.e. a text node), thencontinue
as again we can't modify any text. - 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.
var a = document.getElementsByTagName('a');
for (var i = 0, len = a.length ; i < len ; i += 1) {
a.firstChild.nodeValue = a.href;
}
精彩评论