Travis Northcutt
Travis Northcutt

Reputation: 25036

Modifying the src attribute of an image tag with javascript

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 page.

Upvotes: 0

Views: 158

Answers (4)

keeganwatkins
keeganwatkins

Reputation: 3686

if you are using jQuery >= 1.1:

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

Upvotes: 0

Ilmari Karonen
Ilmari Karonen

Reputation: 50328

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

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

Upvotes: 2

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

Upvotes: 2

Quentin
Quentin

Reputation: 943214

You don't need to use a regular expression.

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

Upvotes: 0

Related Questions