Javascript:在HTML中转义双引号

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

内容简介:翻译自: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


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

查看所有标签

猜你喜欢:

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

How to Design Programs, 2nd Edition

How to Design Programs, 2nd Edition

Matthias Felleisen、Robert Bruce Findler、Matthew Flatt、Shriram Krishnamurthi / MIT Press / 2018-5-4 / USD 57.00

A completely revised edition, offering new design recipes for interactive programs and support for images as plain values, testing, event-driven programming, and even distributed programming. This ......一起来看看 《How to Design Programs, 2nd Edition》 这本书的介绍吧!

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试