1

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?

Brock Adams
  • 90,639
  • 22
  • 233
  • 295
iActivist
  • 37
  • 1
  • 1
  • 5

2 Answers2

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;
}
Community
  • 1
  • 1
Brock Adams
  • 90,639
  • 22
  • 233
  • 295
  • Thanks! That works perfectly. However how could I make the links open in a new tab when clicked? – iActivist Sep 01 '14 at 13:28
  • The smart way is just to middle-click the links. Otherwise, add `link.target = "_blank";` just after the `link.href...` line in the code. `"_blank"` forces the link to open in a new tab (if you set your browser preferences normally). – Brock Adams Sep 01 '14 at 21:26
0

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>'
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274