有人知道一个简单的方法来转义HTML从字符串在jQuery?我需要能够传递一个任意字符串,并有它正确转义显示在HTML页面(防止JavaScript/HTML注入攻击)。我确信可以通过扩展jQuery来实现这一点,但目前我对框架的了解还不够,无法实现这一点。
当前回答
在mustache.js中也有解决方案
var entityMap = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'/': '/',
'`': '`',
'=': '='
};
function escapeHtml (string) {
return String(string).replace(/[&<>"'`=\/]/g, function (s) {
return entityMap[s];
});
}
其他回答
在mustache.js中也有解决方案
var entityMap = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'/': '/',
'`': '`',
'=': '='
};
function escapeHtml (string) {
return String(string).replace(/[&<>"'`=\/]/g, function (s) {
return entityMap[s];
});
}
2简单的方法,不需要JQUERY…
你可以像这样编码字符串中的所有字符:
function encode(e){return e.replace(/[^]/g,function(e){return"&#"+e.charCodeAt(0)+";"})}
或者只针对主要字符担心&,换行符,<,>,"和'像:
function encode(r){ return r.replace(/[\x26\x0A\<>'"]/g,function(r){return"&#"+r.charCodeAt(0)+";"}) } var myString='Encode HTML entities!\n"Safe" escape <script></'+'script> & other tags!'; test.value=encode(myString); testing.innerHTML=encode(myString); /************* * \x26 is &ersand (it has to be first), * \x0A is newline, *************/ <p><b>What JavaScript Generated:</b></p> <textarea id=test rows="3" cols="55"></textarea> <p><b>What It Renders Too In HTML:</b></p> <div id="testing">www.WHAK.com</div>
这是一个简洁明了的JavaScript函数。它会将诸如"a few < many"这样的文本转义为"a few <许多”。
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, ''');
}
很容易使用下划线:
_.escape(string)
下划线是一个实用库,它提供了很多原生js不提供的功能。还有lodash,它是与下划线相同的API,但被重写以提高性能。
ES6一行程序的解决方案来自mustache.js
const escapeHTML = str => (str+'').replace(/[&<>"'`=\/]/g, s => ({'&': '&','<': '<','>': '>','"': '"',"'": ''','/': '/','`': '`','=': '='})[s]);