Ryan
Ryan

Reputation: 35

Which characters to escape in string consisting of HTML tags and attributes?

I have a document.write statement that I'm using to write some HTML. My question is, do I need to escape anything more than the / and "" ?

document.write('<div style=\"display:none;\"><\/div>');

Upvotes: 1

Views: 82

Answers (2)

Quentin
Quentin

Reputation: 943537

You need to escape:

  • ' because that character is used to delimit the string
  • \ because that is an escape character
  • new lines (as \n) since you cannot have a literal new line in the middle of a string in JavaScript

You do not need to escape " since they are not used to delimit this string.

You do not need to escape / except when it immediately follows a <, and even then only when you have HTML inside a <script> element instead of in an external file (but it does no harm to do so the rest of the time).

Upvotes: 2

Bojangles
Bojangles

Reputation: 101483

You don't even need to escape the double quotes in this string - that's only necessary if you enclose your string with double quotes.

You shouldn't need to escape your /es either; they don't break the string and document.write() (afaik) allows plain HTML to be inserted.

Upvotes: 3

Related Questions