我使用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编码?
没有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 >
您不应该为了将值从一个输入字段转移到另一个输入字段而对值进行转义/编码。
<form>
<input id="button" type="button" value="Click me">
<input type="hidden" id="hiddenId" name="hiddenId" value="I like cheese">
<input type="text" id="output" name="output">
</form>
<script>
$(document).ready(function(e) {
$('#button').click(function(e) {
$('#output').val($('#hiddenId').val());
});
});
</script>
JS不会插入原始HTML或其他东西;它只是告诉DOM设置value属性(或属性;不确定)。无论哪种方式,DOM都可以为您处理任何编码问题。除非你在做一些奇怪的事情,比如使用document。写或eval, html编码将是有效透明的。
如果你正在讨论生成一个新的文本框来保存结果……还是那么简单。只需要将HTML的静态部分传递给jQuery,然后设置它返回给你的对象的其余属性/属性。
$box = $('<input type="text" name="whatever">').val($('#hiddenId').val());
var htmlEnDeCode = (function() {
var charToEntityRegex,
entityToCharRegex,
charToEntity,
entityToChar;
function resetCharacterEntities() {
charToEntity = {};
entityToChar = {};
// add the default set
addCharacterEntities({
'&' : '&',
'>' : '>',
'<' : '<',
'"' : '"',
''' : "'"
});
}
function addCharacterEntities(newEntities) {
var charKeys = [],
entityKeys = [],
key, echar;
for (key in newEntities) {
echar = newEntities[key];
entityToChar[key] = echar;
charToEntity[echar] = key;
charKeys.push(echar);
entityKeys.push(key);
}
charToEntityRegex = new RegExp('(' + charKeys.join('|') + ')', 'g');
entityToCharRegex = new RegExp('(' + entityKeys.join('|') + '|&#[0-9]{1,5};' + ')', 'g');
}
function htmlEncode(value){
var htmlEncodeReplaceFn = function(match, capture) {
return charToEntity[capture];
};
return (!value) ? value : String(value).replace(charToEntityRegex, htmlEncodeReplaceFn);
}
function htmlDecode(value) {
var htmlDecodeReplaceFn = function(match, capture) {
return (capture in entityToChar) ? entityToChar[capture] : String.fromCharCode(parseInt(capture.substr(2), 10));
};
return (!value) ? value : String(value).replace(entityToCharRegex, htmlDecodeReplaceFn);
}
resetCharacterEntities();
return {
htmlEncode: htmlEncode,
htmlDecode: htmlDecode
};
})();
这是ExtJS的源代码。
编辑:这个答案是很久以前发布的,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。
在这里查看一个正在运行的示例。