我使用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编码?
使用这里的一些其他答案,我做了一个版本,在一次传递中替换所有相关字符,而不考虑不同编码字符的数量(只需调用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;
如果你想使用jQuery。我发现了这个:
http://www.jquerysdk.com/api/jQuery.htmlspecialchars
(jquery的一部分。jQuery SDK提供的字符串插件
我认为Prototype的问题在于它扩展了JavaScript中的基本对象,并且与你可能使用过的任何jQuery都不兼容。当然,如果你已经在使用Prototype而不是jQuery,这就不是问题。
编辑:还有这个,这是Prototype的字符串实用工具的jQuery端口:
http://stilldesigning.com/dotstring/
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的源代码。