Reputation: 373
I'm building a simple find and replace script that finds a larger version of an image if it exists in the same directory.
I can't seem to get it right or doesn't appear to be working.
If I have an small image, I want jQuery to replace it with a larger version.
Example of Small Image:
<img src="/images/sub/1234S.jpg" />
Example of Large image to replace the small version with:
<img src="/images/sub/1234L.jpg" />
So all it is, is just to replace 'S' with 'L' this is relative throughout the whole of my images. This is always the last character of the url before the file extension.
I'm not looking for a 'mass' replace 'S' with 'L' as some image filenames supplied do contain the letters 'L' & 'S' within. It's only the last character.
I've got this so far that adds 'L' to the end.. but I can't seem to strip out the 'S'.
var imageType = images[i].src.substr(-4);
var imageName = images[i].src.substr(0, images[i].src.length - 4);
imageName += "L" + imageType;
I've tried using 'slice' but couldn't get it to work. Any ideas I'd be greatly thankful.
Upvotes: 0
Views: 753
Reputation: 48211
If you are certain that all your images have a 3-letter extension, you can do it like this:
var imageType = images[i].src.substr(-4);
var imageName = images[i].src.substr(0, images[i].src.length - 5);
imageName += "L" + imageType;
(Basicaly, just replacing ...images[i].src.length - 4...
with ...images[i].src.length - 5...
.)
For a more "robust" solution (e.g. accounting for multiple file-types and variable extension length), you can use a regular expression:
var regex = /S(\.[^\.]+)$/;
...
images[i].src.replace(regex, "L" + "$1");
...
Upvotes: 0
Reputation: 253486
Given the HTML:
<img src="/images/sub/1234L.jpg" />
And the presumption that you wish to change between large and small images on the click-event:
$('img').on('click', function(){
$(this).prop(function(i,s){
return s.replace(/(S|L)\.jpg$/,function(a){
console.log(a);
return (a === 'S' ? 'L' : 'S') + '.jpg';
});
});
});
Upvotes: 0
Reputation: 57105
Try
var len = images[i].src.lastIndexOf('.');
var imageType = images[i].src.substr(len);
imageName = images[i].src.substr(0,len-1)+'L'+imageType;
Upvotes: 0
Reputation: 9800
var imagePath = images[i].src;
var imageType = imagePath.src.substr(-4);
var withoutExtension = ID.substring(imagePath.lastIndexOf(".") + 1);
var final = withoutExtension + "S" + imageType ;
Upvotes: 0
Reputation: 394
You can use a regular expression to swap out 'S' for 'L'
"/images/sub/1234S.jpg".replace(/S.jpg$/, 'L.jpg')
Upvotes: 1