最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to change img src string from ending with _m to _t using jquery for a set of images - Stack Overflow

programmeradmin7浏览0评论

I was hoping to get a nice push in the right direction I would like to change the ending of my images sources string... i hope i worded that right.

Anyway my current src's are reading:

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

I would like to change it to:

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

Any idea guys...Thanks!

I was hoping to get a nice push in the right direction I would like to change the ending of my images sources string... i hope i worded that right.

Anyway my current src's are reading:

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

I would like to change it to:

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

Any idea guys...Thanks!

Share Improve this question edited May 8, 2010 at 1:17 BalusC 1.1m376 gold badges3.6k silver badges3.6k bronze badges asked May 8, 2010 at 0:53 TikaL13TikaL13 1,4888 gold badges24 silver badges50 bronze badges 0
Add a ment  | 

5 Answers 5

Reset to default 10

This one is a bit safer:

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

Else you may risk URL's like /bat_man/images/oh_my_god_m.png to end up as /bat_tan/images/oh_my_god_m.png when using eKek0's answer.


Explanation of the regex /_m(\.[^.]+)?$/:

  • /.../ are just pattern borders.
  • _m matches literal _m.
  • (...) match grouping, the first one ends as $1 in result.
  • \. matches literal .. Because . is a special char in regex, it's escaped by \.
  • [...] represents group of characters.
  • ^. matches everything but literal .. Because it's inside a group, escaping is not needed.
  • + matches one or more characters.
  • ? previous group is optional (for the case that there's no file extension).
  • $ match must occur at end of string (and thus not in the middle or so).
$(img).each(function () {
  var src = $(this).attr('src');
  $(this).attr('src', src.replace("_m", "_t");
});

No need for jQuery on this one:

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');
});

I haven't 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'));
});

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

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论