简体   繁体   English

JavaScript:在HTML中转义双引号

[英]JavaScript: Escaping double quotes in HTML

How can I prevent the images[i].title below from breaking the HTML if it contains double quotes? 如果它包含双引号,如何防止下面的images[i].title打破HTML?

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

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. 这将替换所有引号,您最终会使用双引号,并且它们以有效的HTML格式表示。

You can use the replace() method to escape the double quotes: 您可以使用replace()方法来转义双引号:

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. 结果将是一个有效的JavaScript字符串,但它不能用作HTML标记,因为HTML解析器不理解反斜杠转义。 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 + "' />";
}
var_name.replace(/\"/gi, '%22');

That's the one you're looking for. 这就是你要找的那个。 Even if your colors look "off" in Visual Studio. 即使您的颜色在Visual Studio中看起来“关闭”。

\\ escapes the following quote. \\逃脱以下引用。

gi does a replace for all occurrences. gi替换所有事件。

You can call replace on your title string: 您可以在标题字符串上调用replace:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM