Zgbrell
Zgbrell

Reputation: 159

How to update relative img src tag to an absolute path using javascript

I have a web application that is pulling in an RSS feed from an external resource. Some of the images being pulled in from the feed are relative paths such as /assets/images/image.jpg. The images with relative paths end up being 404's because they do not call back to the external resource for it to be an absolute path like externalsource.com/assets/images/image.jpg. I want to write a javascript function that collects all of the img src tags on the page and ensures that they are all absolute paths. I have no problem collecting all of the img srcs but cannot replace them with the absolute url. When printing out the img srcs, the url from the resource that is pulling in the feed is applied to the url. Like resource/assets/images/image.jpg

Here is what I have thus far:

var images = document.getElementsByTagName('img');
var srcList = [];
for(var i = 0; i < images.length; i++) {
var pattern = new RegExp('^https?:\/\/fiddle\.jshell\.net(\/)');
if (pattern.test(images[i].src)){
    var sources = images[i].src;
        images[i].src = sources.replace("^https?:\/\/fiddle\.jshell\.net(\/)", "http://duo.com");
   console.log(images[i].src);  
}else{
    console.log("no match");    
}
}

I am collecting all of the srcs, comparing them to a regex to see if it matches the resource url, and replacing it with the url from the external resource. Unfortunately, the replacing the url portion is not working whatsoever. It needs to be pure javascript and no jquery.

Any help is really appreciated!

Upvotes: 1

Views: 1853

Answers (1)

gyre
gyre

Reputation: 16779

It looks like you passed a string to the first argument of String#replace:

images[i].src = sources.replace("^https?:\/\/fiddle\.jshell\.net(\/)", "http://duo.com")

You probably meant to pass a regular expression (note the use of / rather than "; this represents a regex literal in JS):

images[i].src = sources.replace(/^https?:\/\/fiddle\.jshell\.net(\/)/, "http://duo.com")

However, I would advise that the majority of your looping and testing logic be reduced to a single call to replace within a forEach loop, like so:

[].forEach.call(document.getElementsByTagName('img'), function (image) {
  image.src = image.src.replace(/^https?:\/\/fiddle\.jshell\.net\//, 'http://duo.com/')
  console.log(image.src)
})
<img src="http://fiddle.jshell.net/favicon.ico">

Upvotes: 1

Related Questions