-1

What I'm trying to do is getting a JS parameter to replace an image SRC with a custom URL using a URL parameter.

Example of parameter:

https://example.com?i=https://example.org/img.jpg
  • 1
    [Read the value from the querystring](https://stackoverflow.com/a/901144/519413), then set the image `src` in either [jQuery](https://stackoverflow.com/a/554289/519413) or plain [Javascript](https://stackoverflow.com/a/11722422/519413) – Rory McCrossan Jan 06 '22 at 16:06
  • https://jsfiddle.net/krg6jqvh/1/ – sidhewsar Jan 11 '22 at 05:59
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Jan 14 '22 at 08:05

1 Answers1

0

There are a few ways to do this and I hope this gets you started (I have not tested this code):

function getUrlVars () {
    let vars = {};
    const p = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,k,v) {
      vars[k] = v;
    });
    return vars;
}

const src = getUrlVars('i');
const img = document.getElementById('image-id-here');
img.src = src;

The getUrlVars is a generic function I often use. It's likely more complicated than what you need.

A word of waring; you should do the extra work/research to validate the content of the URL parameter before inserting into into your page.

donohoe
  • 13,411
  • 4
  • 35
  • 56