user2613041
user2613041

Reputation: 43

Use of quotation marks

Why does this line of code produce the desired results:

document.getElementById('ID').style.backgroundImage = 'url('+ variable +')';

While this line does not:

document.getElementById('ID').style.backgroundImage = "url('+ variable +')";

How do I use quotes in JavaScript?

Upvotes: 0

Views: 39

Answers (1)

Weather Vane
Weather Vane

Reputation: 34585

In Javascript the single and double quote marks are interchangeable but must be using in matching pairs. If your text already contains one style, you can use the other style to preserve the one you want to use as part of the text. So suppose variable = "mypage" then

'url('+ variable +')'

will encode a string as

url(mypage)

But

"url('+ variable +')"

will encode this literally, operators, variable name and all

url('+ variable +')

An example of where you might want to do this is

myname = "John";
sentence = 'My name is "' + myname + '".';

which will give

My name is "John".

Upvotes: 1

Related Questions