我使用JavaScript从隐藏字段中拉出一个值并在文本框中显示它。隐藏字段中的值被编码。
例如,
<input id='hiddenId' type='hidden' value='chalk & cheese' />
被卷入
<input type='text' value='chalk & cheese' />
通过一些jQuery来获取隐藏字段的值(在这一点上,我失去了编码):
$('#hiddenId').attr('value')
问题是当我读粉笔&cheese从隐藏字段,JavaScript似乎失去了编码。我不希望价值是粉笔和奶酪。我想要字面上的amp;被保留。
是否有JavaScript库或jQuery方法可以对字符串进行html编码?
编辑:这个答案是很久以前发布的,htmlDecode函数引入了一个XSS漏洞。它已被修改,将临时元素从div改为textarea,减少XSS的机会。但是现在,我鼓励您像其他回答中建议的那样使用DOMParser API。
我使用这些函数:
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();
}
基本上,textarea元素是在内存中创建的,但它永远不会追加到文档中。
在htmlEncode函数上,我设置了元素的innerText,并检索编码的innerHTML;在htmlDecode函数上,我设置了元素的innerHTML值,并检索了innerText。
在这里查看一个正在运行的示例。
没有Jquery更快。你可以对字符串中的每个字符进行编码:
function encode(e){return e.replace(/[^]/g,function(e){return"&#"+e.charCodeAt(0)+";"})}
或者只关注主要角色(&,inebreaks, <, >, "和'),比如:
函数编码(r) {
返回r.replace (/ [\ x26 \ x0A \ < > "] / g函数(r){返回" & # + r.charCodeAt(0) +”;“})
}
测试。value=encode('编码HTML实体!\n\n"安全"转义<脚本id=\'\'> &有用在<pre>标签!');
testing.innerHTML = test.value;
/*************
* \x26是& &号(必须排在第一位),
* \x0A为换行符,
*************/
<textarea id=test rows="9" cols="55"></textarea>
www.WHAK.com < div id = "测试" > < / div >
使用这里的一些其他答案,我做了一个版本,在一次传递中替换所有相关字符,而不考虑不同编码字符的数量(只需调用replace()),因此对于较大的字符串将更快。
它不依赖于DOM API存在,也不依赖于其他库。
window.encodeHTML = (function() {
function escapeRegex(s) {
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
var encodings = {
'&' : '&',
'"' : '"',
'\'' : ''',
'<' : '<',
'>' : '>',
'\\' : '/'
};
function encode(what) { return encodings[what]; };
var specialChars = new RegExp('[' +
escapeRegex(Object.keys(encodings).join('')) +
']', 'g');
return function(text) { return text.replace(specialChars, encode); };
})();
运行了一次之后,您现在可以调用
encodeHTML('<>&"\'')
得到<>&& #39;
编辑:这个答案是很久以前发布的,htmlDecode函数引入了一个XSS漏洞。它已被修改,将临时元素从div改为textarea,减少XSS的机会。但是现在,我鼓励您像其他回答中建议的那样使用DOMParser API。
我使用这些函数:
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();
}
基本上,textarea元素是在内存中创建的,但它永远不会追加到文档中。
在htmlEncode函数上,我设置了元素的innerText,并检索编码的innerHTML;在htmlDecode函数上,我设置了元素的innerHTML值,并检索了innerText。
在这里查看一个正在运行的示例。