Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to get a number from an image src url with javascript?

I've been searching everywhere and can't find an answer to my question. Maybe I'm asking the wrong questions...

So, my problem is: I have a blogroll that displays the latest post images, where I have sites and blogs from diferent platforms that I want to share with my readers, including WordPress. Most images (thumbnails) are square but the ones from WP blogs are with multiple sizes. Analysing the image src, I was able to find out that replacing the last part of the url did the trick and I can make those images fit with the rest without screwing my site's design. :)

Example:

http://colecaodisney.files.wordpress.com/2014/08/casty.jpg?w=112 <---original image src http://colecaodisney.files.wordpress.com/2014/08/casty.jpg?w=126&h=126&crop=TRUE <---edited by me to fit my blogroll

Since I don't have access to those images src, and with CSS isn't an option due to my blogroll works with javascript, I did this changes with jquery:

img = $(this).find('img').attr('src').replace('?w=112', '?w=126&h=126&crop=TRUE');

The problem is that where is the number 112, that means the width of the thumbnail, isn't always the same number. My solution so far is chain some replaces for every new width number that eventually show up. And I was wondering, and looking everywhere, if there is a way to write that line of code so that it works no matter what the number that represents the width might be...

Thank you for any help.

like image 549
Osvaldo Correia Avatar asked Jan 09 '23 22:01

Osvaldo Correia


2 Answers

Because attr() returns the given attribute for only the first matched element, to change (potentially many) elements I would suggest:

$(this).find('img').prop('src', function(i, src) {
    return src.replace(/(w=\d+)$/, '?w=126&h=126&crop=TRUE');
});

JS Fiddle demo (kindly offered by Brian).

If you need to store a reference the changed images (as from your question), you can chain get() to return an array:

var changedImages = $(this).find('img').prop('src', function(i, src) {
    return src.replace(/(w=\d+)$/, '?w=126&h=126&crop=TRUE');
}).get();

References:

  • find().
  • get().
  • prop().
like image 63
David Thomas Avatar answered Jan 29 '23 14:01

David Thomas


You need to use Regular Expressions.

img = $(this).find('img').attr('src').replace(/w=[0-9]+/, 'w=126&h=126&crop=TRUE');

This will match:

w=(digits)

[0-9] Match a digit

[0-9]+ Match consecutive digits

like image 28
Dávid Szabó Avatar answered Jan 29 '23 14:01

Dávid Szabó