JavaScript:在 HTML 中转义双引号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4475306/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript: Escaping double quotes in HTML
提问by user546587
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 + '" />';
}
采纳答案by Frédéric Hamidi
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. You'll either have to replace double quote characters with single quotes in your image title:
结果将是一个有效的 JavaScript 字符串,但它不能用作 HTML 标记,因为 HTML 解析器不理解反斜杠转义。您必须在图像标题中用单引号替换双引号字符:
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 + "' />";
}
回答by Jeff B
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,'"') + '" />';
}
This replaces allquotes, and you end up with double quotes, and they are represented in an HTML format that is valid.
这将替换所有引号,最终得到双引号,它们以有效的 HTML 格式表示。
回答by NNM aka n0n4m3
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
对所有事件进行替换。
回答by wajiw
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('"',"'") + '" />';
}