AJM*_*AJM 728 html javascript jquery escaping html-escape-characters
我正在使用JavaScript从隐藏字段中提取值并将其显示在文本框中.隐藏字段中的值已编码.
例如,
<input id='hiddenId' type='hidden' value='chalk & cheese' />
Run Code Online (Sandbox Code Playgroud)
被拉进去
<input type='text' value='chalk & cheese' />
Run Code Online (Sandbox Code Playgroud)
通过一些jQuery从隐藏字段中获取值(此时我丢失了编码):
$('#hiddenId').attr('value')
Run Code Online (Sandbox Code Playgroud)
问题是,当我chalk & cheese从隐藏字段中读取时,JavaScript似乎失去了编码.为了逃避chalk & cheese和amp;,我想编码保留.
是否有一个JavaScript库或jQuery方法将对字符串进行HTML编码?
CMS*_*CMS 1062
我使用这些功能:
function htmlEncode(value){
// Create a in-memory element, set its inner text (which is automatically encoded)
// Then grab the encoded contents back out. The element never exists on the DOM.
return $('<textarea/>').text(value).html();
}
function htmlDecode(value){
return $('<textarea/>').html(value).text();
}
Run Code Online (Sandbox Code Playgroud)
基本上,div元素在内存中创建,但它永远不会附加到文档中.
在htmlDecode函数上我设置了div元素,并检索编码的textarea; 在htmlEncode函数上我设置innerText元素的值并innerHTML检索.
在这里查看一个运行示例.
Ane*_*pic 553
jQuery技巧不对引号进行编码,在IE中它会剥离你的空白.
基于Django中的转义模板标签,我猜我已经大量使用/测试了,我做了这个功能,它可以满足需要.
它可以说比空白剥离问题的任何变通方法更简单(也可能更快) - 并且它编码引号,如果您要在属性值中使用结果,这是必不可少的.
function htmlEscape(str) {
return str
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/</g, '<')
.replace(/>/g, '>');
}
// I needed the opposite function today, so adding here too:
function htmlUnescape(str){
return str
.replace(/"/g, '"')
.replace(/'/g, "'")
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/&/g, '&');
}
Run Code Online (Sandbox Code Playgroud)
更新2013-06-17:
在搜索最快的转义时,我发现了一种replaceAll方法的实现:
http
://dumpsite.com/forum/index.php?topic = 4.msg29#msg29(这里也引用:最快替换字符串中所有字符实例的方法)
这里有一些性能结果:http:
//jsperf.com/htmlencoderegex/25
它为replace上面的内置链提供相同的结果字符串.如果有人能解释为什么它更快,我会很高兴的!?
更新2015-03-04:
我刚注意到AngularJS正在使用上面的方法:https:
//github.com/angular/angular.js/blob/v1.3.14/src/ngSanitize/sanitize.js#L435
他们添加了一些改进 - 它们似乎处理了一个模糊的Unicode问题以及将所有非字母数字字符转换为实体.只要您为文档指定了UTF8字符集,我就会觉得后者不是必需的.
我会注意到(4年后)Django仍然没有做这两件事,所以我不确定它们有多重要:https:
//github.com/django/django/blob/1.8b1/django/utils /html.py#L44
更新2016-04-06:
您可能还希望逃避正斜杠/.这对于正确的HTML编码不是必需的,但是OWASP建议将其作为反XSS安全措施.(感谢@JNF在评论中提出建议)
.replace(/\//g, '/');
Run Code Online (Sandbox Code Playgroud)
Thi*_*iff 79
这是一个非jQuery版本,比jQuery .html()版本和.replace()版本快得多.这保留了所有空格,但是像jQuery版本一样,不处理引号.
function htmlEncode( html ) {
return document.createElement( 'a' ).appendChild(
document.createTextNode( html ) ).parentNode.innerHTML;
};
Run Code Online (Sandbox Code Playgroud)
速度: http ://jsperf.com/htmlencoderegex/17

function htmlEncode( html ) {
return document.createElement( 'a' ).appendChild(
document.createTextNode( html ) ).parentNode.innerHTML;
};
function htmlDecode( html ) {
var a = document.createElement( 'a' ); a.innerHTML = html;
return a.textContent;
};
document.getElementById( 'text' ).value = htmlEncode( document.getElementById( 'hidden' ).value );
//sanity check
var html = '<div> & hello</div>';
document.getElementById( 'same' ).textContent =
'html === htmlDecode( htmlEncode( html ) ): '
+ ( html === htmlDecode( htmlEncode( html ) ) );
Run Code Online (Sandbox Code Playgroud)
<input id="hidden" type="hidden" value="chalk & cheese" />
<input id="text" value="" />
<div id="same"></div>
Run Code Online (Sandbox Code Playgroud)
boc*_*oca 32
我知道这是一个旧的,但我想发布一个接受的答案的变体,将在IE中工作而不删除行:
function multiLineHtmlEncode(value) {
var lines = value.split(/\r\n|\r|\n/);
for (var i = 0; i < lines.length; i++) {
lines[i] = htmlEncode(lines[i]);
}
return lines.join('\r\n');
}
function htmlEncode(value) {
return $('<div/>').text(value).html();
}
Run Code Online (Sandbox Code Playgroud)
TJ *_*oll 29
下划线提供_.escape()和_.unescape()执行此操作的方法.
> _.unescape( "chalk & cheese" );
"chalk & cheese"
> _.escape( "chalk & cheese" );
"chalk & cheese"
Run Code Online (Sandbox Code Playgroud)
lee*_*ers 12
好答案.请注意,如果要编码的值是undefined或null使用jQuery 1.4.2,则可能会出现以下错误:
jQuery("<div/>").text(value).html is not a function
要么
Uncaught TypeError: Object has no method 'html'
解决方案是修改函数以检查实际值:
function htmlEncode(value){
if (value) {
return jQuery('<div/>').text(value).html();
} else {
return '';
}
}
Run Code Online (Sandbox Code Playgroud)
小智 11
对于那些喜欢普通javascript的人来说,这是我成功使用的方法:
function escapeHTML (str)
{
var div = document.createElement('div');
var text = document.createTextNode(str);
div.appendChild(text);
return div.innerHTML;
}
Run Code Online (Sandbox Code Playgroud)
FWIW,编码不会丢失.在页面加载期间,标记解析器(浏览器)使用编码.一旦读取并解析了源并且浏览器将DOM加载到内存中,编码就会被解析为它所代表的内容.因此,当您的JS执行以读取内存中的任何内容时,它获取的char就是编码所代表的内容.
我可能在这里严格操作语义,但我希望你理解编码的目的."迷失"这个词听起来似乎有些东西不像它应该的那样工作.
没有Jquery更快.您可以对字符串中的每个字符进行编码:
function encode(e){return e.replace(/[^]/g,function(e){return"&#"+e.charCodeAt(0)+";"})}
Run Code Online (Sandbox Code Playgroud)
或者只是针对主角担心(&,inebreaks,<,>,"和'),如:
function encode(r){
return r.replace(/[\x26\x0A\<>'"]/g,function(r){return"&#"+r.charCodeAt(0)+";"})
}
test.value=encode('Encode HTML entities!\n\n"Safe" escape <script id=\'\'> & useful in <pre> tags!');
testing.innerHTML=test.value;
/*************
* \x26 is &ersand (it has to be first),
* \x0A is newline,
*************/Run Code Online (Sandbox Code Playgroud)
<textarea id=test rows="9" cols="55"></textarea>
<div id="testing">www.WHAK.com</div>Run Code Online (Sandbox Code Playgroud)
Prototype内置了String类.因此,如果您正在使用/计划使用Prototype,它会执行以下操作:
'<div class="article">This is an article</div>'.escapeHTML();
// -> "<div class="article">This is an article</div>"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
620851 次 |
| 最近记录: |