Home > Software engineering >  Including a variable into an url string in javascript
Including a variable into an url string in javascript

Time:10-24

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')";
}

CodePudding user response:

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.

  • Related