Xeptor
Xeptor

Reputation: 477

Replace image link with jQuery

I have an image in a element with an light box image that shows on hover. I want to replace the image in the element with the light box image. My content is matched dynamically, and I cant change the html.

All of my images url ends with /250/250 - and SOME of the lighbox images ends with /400/300 - and I use the script below to replace them:

$('.new-structure .image a img').each(function () {
var src = $(this).attr('src');
$(this).attr('src', src.replace("/250/250", "/400/300"));
});

But some of the light box images has another ending that I cant make the script work for. They look something like this:

/img/0~BC6F034B-3404-4FBA-B26A-9B2990552E72~400~300~1

how do I match the image with the ending of /250/250 with the ones ending with 400~300~1?

Update: Main problem: When I replace 250/250 for 300/400 I don't need to change the full link - they are the same except the ending - when replacing for the ~400~300~1 image i need to swap the full link since its different.

I need to replace this:

 https://mywebsite.com/imgs/2d873287-7eb5-497a-a813-aef655acdb74/250/250

with this:

 https://mywebsite.com/img/0~3B07CED6-08FF-47CD-9D25-D908774F728D~400~300~1

Based on the ending in the url reffering to the image size: /250/250 and ~400~300~1

Update: realized it might be easier to just swap them based on their element classes..

The lightbox image looks like this:

<a class="mainColorbox" href="/img/0~676B9DBB-5D93-4481-B241-74B619F96188~400~300~1"></a>

The target image:

<div class="mainPicture">
<img src="/imgs/7fb6d7bd-b9e7-44b2-a533-a485b93456ac/250/250" class="photo">

Upvotes: 1

Views: 203

Answers (1)

Tobias Sch&#228;fer
Tobias Sch&#228;fer

Reputation: 1358

User a Regex code to replace the strings:

var str = 'some // slashes', replacement = '';
var replaced = str.replace(/\//g, replacement);

Otherwise the slashes will be encoded like in your example.

Find out more here: How to globally replace a forward slash in a JavaScript string?

Upvotes: 1

Related Questions