有誰知道一種簡單的方法來從jQuery的字符串中轉義HTML? 我須要可以傳遞任意字符串並正確地對其進行轉義以顯示在HTML頁面中(防止JavaScript / HTML注入攻擊)。 我敢確定能夠擴展jQuery來作到這一點,可是目前我對框架的瞭解還不夠。 html
escape()
和unescape()
用於對URL(而非HTML)的字符串進行編碼/解碼。 git
實際上,我使用如下代碼片斷來完成不須要任何框架的技巧: github
var escapedHtml = html.replace(/&/g, '&') .replace(/>/g, '>') .replace(/</g, '<') .replace(/"/g, '"') .replace(/'/g, ''');
這是一個乾淨清晰的JavaScript函數。 它將諸如「幾<許多」的文本轉義爲「幾&lt;許多」。 框架
function escapeHtmlEntities (str) { if (typeof jQuery !== 'undefined') { // Create an empty div to use as a container, // then put the raw text in and get the HTML // equivalent out. return jQuery('<div/>').text(str).html(); } // No jQuery, so use string replace. return str .replace(/&/g, '&') .replace(/>/g, '>') .replace(/</g, '<') .replace(/"/g, '"') .replace(/'/g, '''); }
function htmlEscape(str) { var stringval=""; $.each(str, function (i, element) { alert(element); stringval += element .replace(/&/g, '&') .replace(/"/g, '"') .replace(/'/g, ''') .replace(/</g, '<') .replace(/>/g, '>') .replace(' ', '-') .replace('?', '-') .replace(':', '-') .replace('|', '-') .replace('.', '-'); }); alert(stringval); return String(stringval); }
嘗試Underscore.string lib,它與jQuery一塊兒使用。 函數
_.str.escapeHTML('<div>Blah blah blah</div>')
輸出: ui
'<div>Blah blah blah</div>'
mustache.js也提供瞭解決方案 編碼
var entityMap = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''', '/': '/', '`': '`', '=': '=' }; function escapeHtml (string) { return String(string).replace(/[&<>"'`=\/]/g, function (s) { return entityMap[s]; }); }