Derek
Derek

Reputation: 5037

Replace string in url with JQuery

I know this is a really basic question and forgive me for even asking but I cannot seem to get it right for the life of me.

I am using JQuery to get the url from one image src and load it into another image src which I have working fine. However I need to replace the 100x75 part of the url with something like 800x600 so it pulls the larger image.

How would I do that?

Here is an example: Say Im grabbing the image source url with jquery and it looks like this: http://example.com/images/Something_cool-100x75.png I need it to look like this: http://example.com/images/Something_cool-800x600.png

jQuery(document).ready(function($) {
    // this will pull the image I need
    var get_image = $('img.attachment-shop_thumbnail').attr('src');

    //this will assign the image I pulled above to where I need it to go but I need to replace the 100x75 in the filename to 800x600
    $("#sale_img").attr("src", get_image);
});

So if you provide an answer could you tell me how it works because I will also need to change .png to .jpg on some of them as well.. Just not sure how that

Upvotes: 0

Views: 5124

Answers (5)

steinmas
steinmas

Reputation: 398

I think a better implementation would be to have a separate css class for each image (unless there are a lot of them). Instead of worrying about string manipulation of image sources, you can simply change the class.

Upvotes: 0

Karl-André Gagnon
Karl-André Gagnon

Reputation: 33880

You could use regexp :

string.replace(/\d+x\d+/, '800x800')

Basicly, it find a digit (\d) 1 or more time (+) followed by a "x" and the find an other digit one or more time.

It change it for the value you said.

as for the .jpg, you could still use regexp : string.replace(/\.png$/, '.jpg')

Fiddle : http://jsfiddle.net/8mYYZ/

Upvotes: 2

Daniil Grankin
Daniil Grankin

Reputation: 3933

Try this

var get_image = $('img.attachment-shop_thumbnail').attr('src').replace('100x75', '800x600');

Upvotes: 1

Sri Tirupathi Raju
Sri Tirupathi Raju

Reputation: 829

simple javascript replace can do your job

var get_image = $('img.attachment-shop_thumbnail').attr('src');
get_image = get_image.replace("100x75","800x600"); 

in the same way use it for replacing .png to .jpg. so it comes as

var get_image = $('img.attachment-shop_thumbnail').attr('src').replace("100x75","800x600")..replace(".png",".jpg");

Upvotes: 1

Joe Cullinan
Joe Cullinan

Reputation: 562

var old = "http://example.com/images/Something_cool-100x75.png";
var new = old.replace("100x75","800x600");
new = new.replace(".png",".jpg");
alert(new);

Alerts "http://example.com/images/Something_cool-800x600.jpg"

Upvotes: 2

Related Questions