Home > Net >  How can I escape a background image URL
How can I escape a background image URL

Time:11-02

I feel like this might be a stupid question. I am trying to make the background image of a div change based on whatever object is selected.

`

previewBackground.style.backgroundImage = "url(`/images/object.firstName}.png`)";

`

I need to escape the doubles quotes for the URL to fill in the object.firstName property. Can someone help me with the syntax here?

I have tried using single quotes of the URL, as well as . Single quotes don't do the trick, and turn my entire escape my entire URL.

I have also tried a \ but this only affects the following character and feel like there has to be a more efficient way to do this.

Thanks! I am pretty new to JS.

CodePudding user response:

You will want to use the ticks to start and end the entire string. Then include double quotes within the URL and don't forget when using template literals, to start with the dollar sign $

let previewBackground = document.querySelector("#previewBackground");
let object=  {
  firstName: "350x150"
};

previewBackground.style.backgroundImage = `url("https://via.placeholder.com/${object.firstName}")`;
#previewBackground{
width:350px;
height:150px;
border:1px solid #000;
}
<div id="previewBackground"></div>

  • Related