有没有人知道用jQuery从字符串中转义HTML的简单方法?我需要能够传递任意字符串,并将其正确转义以便在HTML页面中显示(防止JavaScript/HTML注入攻击)。我确信有可能通过扩展jQuery来实现这一点,但目前我对框架的了解还不够多。
发布于 2008-08-24 17:22:15
由于您使用的是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>
发布于 2012-08-20 16:21:06
还有the solution from mustache.js
var entityMap = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'/': '/',
'`': '`',
'=': '='
};
function escapeHtml (string) {
return String(string).replace(/[&<>"'`=\/]/g, function (s) {
return entityMap[s];
});
}
发布于 2008-12-17 10:28:45
$('<div/>').text('This is fun & stuff').html(); // "This is fun & stuff"
来源:http://debuggable.com/posts/encode-html-entities-with-jquery:480f4dd6-13cc-4ce9-8071-4710cbdd56cb
https://stackoverflow.com/questions/24816
复制相似问题