JavaScript:在 HTML 中转义双引号
如果下面的 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 + '" />';
}
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 + '" />';
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
因为在我看来似乎没有人有完全正确的答案:
这会替换所有引号,最终会得到双引号,并且它们以有效的 HTML 格式表示。
Since no one seems to have exactly the right answer in my opinion:
This replaces all quotes, and you end up with double quotes, and they are represented in an HTML format that is valid.
您可以使用 replace() 方法来转义双引号:
结果将是一个有效的 JavaScript 字符串,但它不能用作 HTML 标记,因为 HTML 解析器不理解反斜杠转义。您必须在图像标题中将双引号字符替换为单引号:
或者反转标记中的引号类型:
You can use the replace() method to escape the double quotes:
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:
Or invert the quote types in your markup:
这就是您要找的人。即使您的颜色在 Visual Studio 中看起来“不正常”。
\
转义以下引号。gi
对所有出现的情况进行替换。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.您可以对标题字符串调用替换:
You can call replace on your title string: