Skip to content Skip to sidebar Skip to footer

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.

Solution 1:

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)
})
<imgsrc="http://fiddle.jshell.net/favicon.ico">

Post a Comment for "How To Update Relative Img Src Tag To An Absolute Path Using Javascript"