0
var alt = json_data['alt']; // some text
var url = json_data['url']; // some url

var img_url = '<img src=\'/' + url + '?h=100&w=100\' alt=\'' + alt + '\'>';
$('#imagepreview').html(img_url); // translates to <img src="/some_url?h=100&amp;w=100" alt="some_text">

Why does this happen and how can I prevent this?

Cas van Noort
  • 255
  • 3
  • 9
  • 7
    Actually this is good as it produces valid HTML. ampersands must be escaped like this in urls for the HTML code to be valid. So I see no problem here, it should be working. – acme Jun 01 '12 at 13:48
  • Ok, but in this example I want the & not the & – Cas van Noort Jun 01 '12 at 13:51
  • 1
    http://stackoverflow.com/questions/355043/how-do-i-escape-an-ampersand-in-a-javascript-string-so-that-the-page-will-valida – davids Jun 01 '12 at 13:54

3 Answers3

4

&amp; is actually the valid URL, not &

Tallboy
  • 12,847
  • 13
  • 82
  • 173
1

I personally don't see that happen, but nevertheless you should do it this way:

var img = $('<img />', {
    src: '/' + url + '?h=100&w=100',
    alt: alt
}).appendTo('#imagepreview');

That makes sure any escaping is done properly, such as the alt attribute!

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
0

You must use \u0026 instead of &

Cas van Noort
  • 255
  • 3
  • 9