有人知道一个简单的方法来转义HTML从字符串在jQuery?我需要能够传递一个任意字符串,并有它正确转义显示在HTML页面(防止JavaScript/HTML注入攻击)。我确信可以通过扩展jQuery来实现这一点,但目前我对框架的了解还不够,无法实现这一点。
当前回答
因为你使用的是jQuery,你可以设置元素的text属性:
// before:
// <div class="someClass">text</div>
var someHtmlString = "<script>alert('hi!');</script>";
// set a DIV's text:
$("div.someClass").text(someHtmlString);
// after:
// <div class="someClass"><script>alert('hi!');</script></div>
// get the text in a string:
var escaped = $("<div>").text(someHtmlString).html();
// value:
// <script>alert('hi!');</script>
其他回答
如果你转义HTML,只有三个我能想到,这将是真正必要的:
html.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
根据您的用例,您可能还需要执行“to "”之类的操作。如果列表足够大,我就使用数组:
var escaped = html;
var findReplace = [[/&/g, "&"], [/</g, "<"], [/>/g, ">"], [/"/g, """]]
for(var item in findReplace)
escaped = escaped.replace(findReplace[item][0], findReplace[item][1]);
encodeURIComponent()只会对url进行转义,而不会对HTML进行转义。
很容易使用下划线:
_.escape(string)
下划线是一个实用库,它提供了很多原生js不提供的功能。还有lodash,它是与下划线相同的API,但被重写以提高性能。
转义html特殊(UTF-8)
function htmlEscape(str) {
return str
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/\//g, '/')
.replace(/=/g, '=')
.replace(/`/g, '`');
}
对于unescape html特殊(UTF-8)
function htmlUnescape(str) {
return str
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/'/g, "'")
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(///g, '/')
.replace(/=/g, '=')
.replace(/`/g, '`');
}
你可以很容易地用香草js做到这一点。
只需在文档中添加一个文本节点。 它将被浏览器转义。
var escaped = document.createTextNode("<HTML TO/ESCAPE/>")
document.getElementById("[PARENT_NODE]").appendChild(escaped)
因为你使用的是jQuery,你可以设置元素的text属性:
// before:
// <div class="someClass">text</div>
var someHtmlString = "<script>alert('hi!');</script>";
// set a DIV's text:
$("div.someClass").text(someHtmlString);
// after:
// <div class="someClass"><script>alert('hi!');</script></div>
// get the text in a string:
var escaped = $("<div>").text(someHtmlString).html();
// value:
// <script>alert('hi!');</script>