How to relink/delink image URLs to point to the full image?

南笙酒味 提交于 2019-11-28 11:38:19

问题


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=&amp;gid=4933418&amp;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=&amp;gid=4933418&amp;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

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