How to change img src line from end to _m to _t using jquery for image set

I was hoping to get a good push in the right direction, I would like to change the end of the line of image sources ... I hope this is correct.

Anyway, my current src reads:

<img src="something/something/12345_m.jpg" />

I would like to change it to:

<img src="something/something/12345_t.jpg" />

Any ideas guys ... Thanks!

+5
source share
5 answers

This is a bit safer:

$('img').each(function () {
    var src = $(this).attr('src');
    $(this).attr('src', src.replace(/_m(\.[^.]+)?$/, '_t$1');
});

If you use eKek0, you could jeopardize a URL such /bat_man/images/oh_my_god_m.pngas /bat_tan/images/oh_my_god_m.png.


Regular expression explanation /_m(\.[^.]+)?$/:

  • /.../ - these are just the borders of the picture.
  • _mmatches literal _m.
  • (...) , $1 .
  • \. .. . char , \.
  • [...] .
  • ^. , .. , .
  • + .
  • ? ( , ).
  • $ (, , ).
+10
$(img).each(function () {
  var src = $(this).attr('src');
  $(this).attr('src', src.replace("_m", "_t");
});
+1

jQuery :

function argsToArray(args) {
  var r = []; for (var i = 0; i < args.length; i++)
    r.push(args[i]);
  return r;
}
argsToArray(document.getElementsByTagName('img')).forEach(function(img) {
  img.src = img.src.split('_m').join('_t');
});
+1

img.src = "<image source>";where the variable imgis searched from the DOM as follows: document.getElementByTagName('img')[0]or this: document.getElementById('image')(if <img id="image" />), learn about the HTML DOM to do this.

0
source

I have not tested it, but this should work:

$('img').each(function () {
    var src = $(this).attr('src');
    $(this).attr('src', src.replace(/_m\.(png|jpg|jpeg|gif)$/, '_t.$1'));
});
0
source

All Articles