Search code examples
jquerywordpressimageresolutionsrc

Remove the last characters from image source


I'm building a Wordpress site which contains lots of heavy images. By loading the 'large' version of the images that wordpress generates I think I can minimize the page load instead of getting the full size of them. But on desktops I want the full sized images to be loaded instead of the 'large' sized ones.

I've used the following code to change the image source if the page is loaded on a desktop:

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

But since all pictures aren't 1024x682 in their 'large' resolution I need another solution to my problem. Is it possible to instead of replacing -1024x682 in the image src, just remove the last 9 characters (before the file extension of course)?


Solution

  • You can update your code to something like below

    var src = $(this).attr('src');
    var extension = src.substring(src.lastIndexOf(".")); // gets the extension
    var imageName = src.substring(0, src.lastIndexOf(".")); // gets the file name
    imageName = imageName.replace(imageName.substring(imageName.length-9), ""); // replace the last 9 characters with empty string
    $(this).attr('src', imageName + extension);