问题
I'm trying to change the following url:
http://www.example.net/?image=full&action=view&imageid=1361
into
http://www.anothersite.com/download&id=1361&thumb=0
while preserving the id (1361
in the example)
(change 'example.net/?image=full&action=view&image' to 'anothersite.com/download&' and add '&thumb=0' at the end of the url)
How do I write a GreaseMonkey script for that?
ps. I've already googled it and copied the code below. It's working, but the problem is it adds '&thumb=0' to the other link too (not just the 'replaced' link(s))
// ==UserScript==
// @name whatever
// @namespace lii
// @description redirect to anothersite
// @include http://www.example.net/?image=full&action=view*
// @version 1
// @grant none
// ==/UserScript==
var links,thisLink;
links = document.evaluate("//a[@href]",
document,
null,
XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,
null);
for (var i=0;i<links.snapshotLength;i++) {
var thisLink = links.snapshotItem(i);
thisLink.href = thisLink.href.replace('http://www.example.net/?image=full&action=view&image',
'http://www.anothersite.com/download&') + "&thumb=0";
}
回答1:
Try this:
thisLink.href = thisLink.href.replace(RegExp('http://www\\.example\\.net/\\?image=full&action=view&image(.*)'),
'http://www.anothersite.com/download&$1&thumb=0');
It applies regular expression to match the URL and extract the id and inserts it as $1
into the resulting string.
More info at MDN.
来源:https://stackoverflow.com/questions/30540877/script-to-modify-a-url-in-greasemonkey