问题
I'm trying to change the URL's of a webpage on the fly using Greasemonkey.
The target page has links like:
<a name="217258323" href="http://foobar.net/photo/217258323/?pgid=&gid=4933418&page=0">
<img style="border:1px solid #fff;padding:5px;background:#fff;"
height="120" width="160" alt="Gallery pic 1 of 20 pics" border="0"
src="http://i.foo.net/images/thumb/52/217/217258323.jpg">
</a>
I want to change them like:
<a name="217258323" href="http://i.foo.net/images/full/52/217/217258323.jpg">
<img style="border:1px solid #fff;padding:5px;background:#fff;"
height="120" width="160" alt="Gallery pic 1 of 20 pics" border="0"
src="http://i.foo.net/images/thumb/52/217/217258323.jpg">
</a>
That is, I want replace the link href with the image src value -- but with /full/ instead of /thumb/.
Any sample scripts or examples to achieve what I'm trying to do?
回答1:
This is a standard image relink/delink problem, and you can probably find several premade userscripts for just about any site.
But don't try to do this with just regex, that way lies madness (and broken scripts).
Here's how to relink your example using DOM methods:
var thumbImgs = document.querySelectorAll ("a > img[src*='/thumb/']");
for (var J = thumbImgs.length-1; J >= 0; --J) {
var img = thumbImgs[J];
var lnkTarg = img.src.replace (/\/thumb\//, "/full/");
var link = img.parentNode;
link.href = lnkTarg;
}
回答2:
I think you want something like this,
> var s = '<a name="217258323" href="http://foobar.net/photo/217258323/?pgid=&gid=4933418&page=0">\n <img style="border:1px solid #fff;padding:5px;background:#fff;"\n height="120" width="160" alt="Gallery pic 1 of 20 pics" border="0"\n src="http://i.foo.net/images/thumb/52/217/217258323.jpg">\n </a>';
undefined
> var f = s.replace(/(href=")[^"]*([\s\S]*?)(src=")([^"]*)([\S\s]+?<\/a>)/g, '$1$4$2$3$4$5');
undefined
> var result = f.replace(/thumb(?=.*thumb)/, 'full');
undefined
> result
'<a name="217258323" href="http://i.foo.net/images/thumb/52/217/217258323.jpg">\n <img style="border:1px solid #fff;padding:5px;background:#fff;"\n height="120" width="160" alt="Gallery pic 1 of 20 pics" border="0"\n src="http://i.foo.net/images/thumb/52/217/217258323.jpg">\n </a>'
来源:https://stackoverflow.com/questions/25603673/how-to-relink-delink-image-urls-to-point-to-the-full-image