moey
moey

Reputation: 10897

JavaScript: escape vs. unescape

I saw some sites were using the JavaScript escape() and unescape() functions interchangeably.

Some used:

document.write('<img height="1" width="1" style="border-style:none;" alt="" src="..."/>');

whereas, this was also pretty common (note: they first "escape" the string, then "unescape" it):

document.write(unescape('%3Cimg%20height%3D%221%22%20width%3D%221%22%20style%3D%22border-style%3Anone%3B%22%20alt%3D%22%22%20src%3D%22...%22/%3E'));

The latter seems to achieve the same as the former, only using a longer way. Any differences in these two methods?

Upvotes: 2

Views: 3993

Answers (3)

Cees Timmerman
Cees Timmerman

Reputation: 19664

Line breaks and similar quotes to the JavaScript's break the parser.

var test = "This "string", for example.";

Backslash escapes are built-in, so this works:

var test = "This \"string\", for example.";

But then you'd have to find a function to escape ", ', \n, \r, and from the other answers, < and > as well.

escape() already encodes strings to remove most non-alphanumeric characters, and unescape() undoes escape().

escape("It's > 20% less complicated this way.")

"It%27s%20%3E%2020%25%20less%20complicated%20this%20way."

If the escaped spaces bother you, try:

escape("It's > 20% less complicated this way.").replace(/%20/g, " ")

"It%27s %3E 20%25 less complicated this way."

Upvotes: 0

David M&#229;rtensson
David M&#229;rtensson

Reputation: 7620

For xhtml compliance you cannot have any HTML tag (<div></div> or <img />) inside a script block so either you use unescape or concatenation '<' + 'div...' or you add //<![CDATA[ ... //]]> inside the script block to pass validation.

Upvotes: 0

mikerobi
mikerobi

Reputation: 20878

It isn't clear in this example. But you can not have inline scripts containing <script> or </script> inside of a string, or the browser will try and process it like a script tag.

Escaping and unescaping html avoids this problem. A better solution is to put the script in a separate file from the html document.

Upvotes: 1

Related Questions