Javascript: escaping double quotes in HTML

How can I prevent images[i].title below from hacking 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 + '" />'; } 
+7
source share
4 answers

You can use the replace () method to avoid 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, '\\"') + '" />'; } 

EDIT: The result will be a valid Javascript string, but will not work as HTML markup, because the HTML parser does not understand reverse reset screens. You will have to either replace the double quotes with single quotes in the image header:

 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 types of quotes 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 + "' />"; } 
+6
source

Since no one seems to have the correct 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 the quotes all , and you get double quotes, and they are presented in the correct html format.

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

This is the one you are looking for. Even if your colors look “off” in Visual Studio.

\ avoids the following quote. gi replaces all occurrences.

+2
source

You can call replace on the title bar:

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

All Articles