Reputation: 1114
The way of what I have done inn this code, is whatever number of images you want, all you need is to have them with path as css class.
Sub.html:
<div>
<img src ="../images/aa.png" class="path"/>
<img src ="../images/bb.png" class="path"/>
<img src ="../images/cc.png" class="path"/>
<img src ="../images/dd.png" class="path"/>
<img src ="../images/ee.png" class="path"/>
</div>
Jquery:
$('#main').load( "../sub.html",function(data){
var newPath = 'css/images/';
$.each($('.path'), function(index){
var originalSource = $(this).attr('src');
// Replacing the source
var newSource = newPath + originalSource.substr(originalSource.lastIndexOf('/') + 1);
// Setting the new value of src
$(this).attr('src', newSource);
});
});
Everything is working fine, path is getting added to the images.
URL: localhost:8080/abc/def/ghi/jkl/css/images/aa.png.
But required url is localhost:8080/abc/def/css/images/aa.png.
How do I remove ghi
and jkl
from url..
And jkl
values keep changes where as ghi
is static value it will be same everytime.
Upvotes: 0
Views: 172
Reputation: 948
Use a regular expression like this:
var newSource = replace(/\/ghi\/[^\/]*/, '');
The [^\/]
part matches everything but a /
.
This is needed to get the variable part of the url after /ghi
to the next /
.
So your code would become:
$('#main').load( "../sub.html",function(data){
$.each($('.path'), function(index){
var originalSource = $(this).attr('src');
// Replacing the source
var newSource = originalSource.replace(/\/ghi\/[^\/]*/, '');
// Setting the new value of src
$(this).attr('src', newSource);
});
});
Edit
See this JSFiddle. I used a simplified version of your code and everything works as expected. If you inspect the images you can see that the src attribute is replaced as it should be.
Upvotes: 1