使用jQuery转义HTML字符串
时间:2020-03-05 18:42:31 来源:igfitidea点击:
有谁知道一种简单的方法来从jQuery中的字符串中转义HTML?我需要能够传递任意字符串,并正确地对其进行转义以显示在HTML页面中(防止JavaScript / HTML注入攻击)。我敢肯定可以扩展jQuery来做到这一点,但是目前我对框架的了解还不够。
解决方案
回答
如果我们转义使用HTML,那么我认为只有三点是真正必要的:
html.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
根据用例,我们可能还需要执行诸如从""到""的操作。如果列表足够大,我将使用一个数组:
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进行转义。
回答
由于我们使用的是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>
回答
$('<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