Javascript:在HTML中转义双引号

栏目: Html · 发布时间: 6年前

内容简介:翻译自:https://stackoverflow.com/questions/4475306/javascript-escaping-double-quotes-in-html
如果它包含双引号,我如何防止图像[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 + '" />';
}
您可以使用 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, '\\"') + '" />';
}

编辑:结果将是一个有效的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, "'") + '" />';
}

或者反转标记中的报价类型:

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

翻译自:https://stackoverflow.com/questions/4475306/javascript-escaping-double-quotes-in-html


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Tangled Web

The Tangled Web

Michal Zalewski / No Starch Press / 2011-11-26 / USD 49.95

"Thorough and comprehensive coverage from one of the foremost experts in browser security." -Tavis Ormandy, Google Inc. Modern web applications are built on a tangle of technologies that have been de......一起来看看 《The Tangled Web》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

随机密码生成器
随机密码生成器

多种字符组合密码

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码