开发者

Modifying the src attribute of an image tag with javascript

开发者 https://www.devze.com 2023-04-10 07:48 出处:网络
I\'m trying to perform a find/replace on the src attribute of an image tag, to remove part of the filename of the image. I assume I need to use str.replace(), but I\'m not sure how to write the regex

I'm trying to perform a find/replace on the src attribute of an image tag, to remove part of the filename of the image. I assume I need to use str.replace(), but I'm not sure how to write the regex to accomplish what I'm trying to do.

The src attribute is currently

http://domain.com/path/to/file/D063DC58-6051-4B24-8CDC-D4525F72A150_tn.jpg

where /to/file/xxxxxxx_tn.jpg will vary, with the filename always ending in _tn.jpg. I'd like to remove the _tn from each instance on the pag开发者_StackOverflowe.


var images = document.getElementsByTagName('img');

for (var i = 0; i < images.length; i++) {
    images[i].src = images[i].src.replace('_tn.jpg', '.jpg');
}


var srcValue = "http://domain.com/path/to/file/D063DC58-6051-4B24-8CDC-D4525F72A150_tn.jpg";

var newSrcValue = srcValue.replace(/[A-Z0-9\-]+_tn/, 'xxxxx_tn');


You don't need to use a regular expression.

referenceToImage.src = referenceToImage.src.replace('_tn', '');


if you are using jQuery >= 1.1:

$("img").attr("src", function(i, val) {
    return val.replace("_tn.jpg", ".jpg");
});
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号