I adapted one of the answers from the referenced question, but added the ability to define an explicit mapping for character names.
var char_names = {
160:'nbsp',
161:'iexcl',
220:'Uuml',
223:'szlig',
196:'Auml',
252:'uuml',
};
function HTMLEncode(str){
var aStr = str.split(''),
i = aStr.length,
aRet = [];
while (--i >= 0) {
var iC = aStr[i].charCodeAt();
if (iC < 32 || (iC > 32 && iC < 65) || iC > 127 || (iC>90 && iC<97)) {
if(char_names[iC]!=undefined) {
aRet.push('&'+char_names[iC]+';');
}
else {
aRet.push('&#'+iC+';');
}
} else {
aRet.push(aStr[i]);
}
}
return aRet.reverse().join('');
}
var text = "Übergroße Äpfel mit Würmer";
alert(HTMLEncode(text));