JavaScript: Escaping double quotes in HTML

别来无恙 提交于 2019-12-10 13:06:15

问题


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 + '" />';
}

回答1:


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 + "' />";
}



回答2:


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.




回答3:


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.




回答4:


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('"',"'") + '" />';
}


来源:https://stackoverflow.com/questions/4475306/javascript-escaping-double-quotes-in-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!