skip to Main Content

I’d like to use JS or JQuery to grab a specific URL parameter and append it to an IMG SRC tag I have embedded in a custom code block on my landing page. Example below:

Example URL – https://www.example.com/page?utm_source=test&[email protected]

Desired IMG SRC – <img src="https://www.example.com/[email protected]">

I’ve combed through a couple of articles that present similar solutions (usually the image src URL itself), but I haven’t been able to get it to work – just out of my depth.

Thank you.

2

Answers


  1. Considering this is our URL: https://www.example.com/page?utm_source=test&[email protected]&quot;;

    const url = window.location.href;
        const email = url.split("email=")[1];
        const imgSrc = "https://www.example.com/example.jpg?email=" + email;
        const imgTag = "<img src='" + imgSrc + "'>";
    
    Login or Signup to reply.
  2. With the help of danish’s answer:

    $(document).ready(function () {
    
        function setToImg(url,param,imageId,imageUrl){
            const urlParam =  url.split(''+param+'=')[1];
            const result =  decodeURI(urlParam).trim();
            const imgSrc = imageUrl+'?'+param+'='+result;
            $('#'+imageId).attr('src',imgSrc);
        }
    
        setToImg('https://www.example.com/page?utm_source=test&[email protected]','email','myImage','image-name.jpeg');
    
        //helper for run function:
        //setToImg('your_url_whith_params','param','your_image_id','your_image_url_without_params');
        //for top page url:
        //setToImg(window.location.href,'email','myImage','image-name.jpeg');
    
        console.log($('div').html()); //for test - remove this line.
    
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div><img id="myImage"></div>

    UPDATE: for get image past src and append new src:

    $(document).ready(function () {
    
        function setToImg(url,param,imageId){
            const urlParam =  url.split(''+param+'=')[1];
            const result =  decodeURI(urlParam).trim();
            const imageUrl = $('#'+imageId).attr('src');
            const imgSrc = imageUrl+'?'+param+'='+result;
            $('#'+imageId).attr('src',imgSrc);
        }
    
        setToImg('https://www.example.com/page?utm_source=test&[email protected]','email','myImage');
    
        //helper for run function:
        //setToImg('your_url_whith_params','param','your_image_id');
        //for top page url:
        //setToImg(window.location.href,'param','your_image_id');
    
        console.log($('div').html());  //for test - remove this line.
    
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div><img id="myImage" src="https://example.com/img/image.jpeg"></div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search