Otishone Otishone - 1 year ago 150
HTML Question

Html encode language signs with javascript/jQuery

I need to encode different languages signs with javascript (mostly german signs). For example I need to have this:

Bemerkung für alles

Encoded to this:

Bemerkung für alles

I search for that and I know that this can do the trick:

$('<div/>').text('<div>Bemerkung für alles</div>').html();

But unfortunately it only encodes some other signs for example: '<', '>', '&' and so on.
Is there any option to encode such signs with javascript/jQuery without creating an array of signs to change and do it manually?

Answer Source

You may encode them to unicode sequence:

var s = "Bemerkung für alles";
//                   vvvvvv--here are ignored chars :a-zA-Z0-9-?!{space}
var r = s.replace(/[^\w -?!]/g, function(c) {
    return '&#'+c.charCodeAt(0)+';';
// r = "Bemerkung f&#252;r alles"
$('<a>').html(r).text() == s //true
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download