Script to modify a URL in greasemonkey

可紊 提交于 2020-01-06 13:54:06

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!