Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Escaping double quotes in HTML

How can I prevent the images[i].title below from breaking the HTML if it contains double quotes?

for (i=0; i<=images.length-1; i++) {
    gallery += '<img width="250" height="250" src="' +  images[i].src + '" title="' + images[i].title + '" />';
}
like image 285
user546587 Avatar asked Dec 17 '10 22:12

user546587


4 Answers

Since no one seems to have exactly the right answer in my opinion:

for (i=0; i<=images.length-1; i++) {
    gallery += '<img width="250" height="250" src="' +  images[i].src +
               '" title="' + images[i].title.replace(/\"/g,'&quot;') + '" />';
}

This replaces all quotes, and you end up with double quotes, and they are represented in an HTML format that is valid.

like image 132
Jeff B Avatar answered Nov 04 '22 13:11

Jeff B


You can use the replace() method to escape the double quotes:

for (var i = 0; i < images.length; ++i) {
    gallery += '<img width="250" height="250" src="' + images[i].src +
               '" title="' + images[i].title.replace(/\"/g, '\\"') + '" />';
}

The result will be a valid JavaScript string, but it won't work as HTML markup, because the HTML parser doesn't understand backslash escapes. You'll either have to replace double quote characters with single quotes in your image title:

for (var i = 0; i < images.length; ++i) {
    gallery += '<img width="250" height="250" src="' + images[i].src +
               '" title="' + images[i].title.replace(/\"/g, "'") + '" />';
}

Or invert the quote types in your markup:

for (var i = 0; i < images.length; ++i) {
    gallery += "<img width='250' height='250' src='" + images[i].src +
               "' title='" + images[i].title + "' />";
}
like image 38
Frédéric Hamidi Avatar answered Nov 04 '22 11:11

Frédéric Hamidi


var_name.replace(/\"/gi, '%22');

That's the one you're looking for. Even if your colors look "off" in Visual Studio.

\ escapes the following quote.

gi does a replace for all occurrences.

like image 45
NNM aka n0n4m3 Avatar answered Nov 04 '22 13:11

NNM aka n0n4m3


You can call replace on your title string:

for ( i=0;i<=images.length-1;i++ ){
    gallery += '<img width="250" height="250" src="' +  images[i].src + '" title="' + images[i].title.replace('"',"'") + '" />';
}
like image 38
wajiw Avatar answered Nov 04 '22 11:11

wajiw