Antonio Ortiz Antonio Ortiz - 1 year ago 61
Javascript Question

Is there a way to explicitly change an images source path using JavaScript?

An HTML page handed off to me which originally have a image path which look something like this...

<img src="img/foo.jpg"

simply need to be changed to a new path.

I have a loop which goes through the collection of images:

container_images = container.getElementsByTagName('img');
imgSrc = /img\//gi,

for (var i = 0; i < container_images.length; i++) {
var images = container_images[i];

if (images.src.indexOf('img') !== -1) {
images.src = images.src.replace(imgSrc, 'new/path/here/');

Now this works perfectly locally however when I run this on my company's QAF server, it appears the server is adding a dev path:

<img src="">

So is there a method other than
which can explicitly wipe out and the old path and put my new path? i.e.

Answer Source

I found such a simple but elegant solution. Instead of testing for a string with indexOf (which would've worked if I didn't have two different environments), I went for a solution which is more direct.

images.src = '/dam/avon-us/landing-pages/rep-news/' +  images.src.split('/').pop();

This first coverts the image path/string to a collection of items in an array, delineated by the forward slash. ['current', 'path', 'foo.jpg'] Then using the pop method return just the last item in the array, which is the file name & extension. foo.jpg and then we simply prepend the path we want the image to have!

Want to say thanks for all the folks who tried to help me!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download