Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Including a variable into an url string in javascript

I’m wondering how to insert the imageId number into the url string, I got confused when there’s a string inside a string.

const imageId = 13935764;

switchBackground.onclick = function(){
  setbg.style.backgroundImage = "url('https://images.pexels.com/photos/'+imageId+'pexels-photo-13366951.jpeg?cs=srgb&dl=pexels-kwnos-iv-13366951.jpg&fm=jpg')";
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can use template literals (backticks)

switchBackground.onclick = function(){
  setbg.style.backgroundImage = `url('https://images.pexels.com/photos/${imageId}pexels-photo-13366951.jpeg?cs=srgb&dl=pexels-kwnos-iv-13366951.jpg&fm=jpg')`;
}

The issue is that the double-quotes is treating the entire string as a literal and not adding in the imageId.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading