Ramiro Tormenta
Ramiro Tormenta

Reputation: 611

How to modify an URL in javascript if it does not exists?

I am loading a set of images with .jpg extension, but some of those images are actually a .png files.

I want to change the URL using the replace method in order to update the url string from .jpg to .png to avoid status of 404 error.

This images are rendering a html template using just javascript.

I followed the next steps:

1

Trying to load image using || operator.

module.exports = (data) => {
  return `
    <img class='img-circle' src='${data.metadata.image || data.metadata.image.replace('.jpg', '.png'}' />
  `
}

2

I found the url-exists package. So I tried to create a function that checks if url exists, if not, replace image extension

const urlExists = require('url-exists')
module.exports = (data) => {
  // function
  function updateUrl (url) {
    urlExists(url, (err, res) => {
      if (res === true) {
        return url
      } else {
        return url.replace('.jpg', '.png')
      }
    })
  }
  return `
    <img class='img-circle' src='${updateUrl(data.metadata.image)} />
  `
}

3

I found this answer that detects if URL exists: https://stackoverflow.com/a/10926978/6005062, so I tried to create other function to retrieve response with the URL modified

module.exports = (data) => {
  // function
  function updateUrl (url) {
    let request = new XMLHttpRequest()
    request.open('GET', url, true)
    request.onreadystatechange = function() {
      if (request.readyState === 4) {
        if (request.status === 404) {
          url = url.replace('.jpg', '.png')
        }
      }
    }
    return url
  }
  return `
    <img class='img-circle' src='${updateUrl(data.metadata.image)}' />
  `
}

Any of those methods shows the new URL. How can I modify an URL in javascript if it does not exists?

Upvotes: 3

Views: 249

Answers (1)

hossein sedighian
hossein sedighian

Reputation: 2035

to handle url with error you can use this

 <img class='img-circle' src='${updateUrl(data.metadata.image)}  onerror="this.src='NEW-URL'"/>

Upvotes: 2

Related Questions