Search code examples
javascriptencodeiso-8859-1

Encoding a String to ISO-8859-1


Is there a way that a can encode my string Olá to Olá in JavaScript? And do this to all accented characters.

My header looks like:

Content-Type: text/html;charset=iso-8859-1

Solution

  • If you already have a proper string, you can do it like this:

    ECMAScript ≥ 6, with Emoji support

    (see: https://medium.com/@giltayar/iterating-over-emoji-characters-the-es6-way-f06e4589516)

    function decimalEscape(s) {
        let buffer = [];
        for(let ch of s) {
            if(ch.codePointAt(0) <= 127) {
                buffer.push(ch);
            } else {
                buffer.push('&#' + ch.codePointAt(0) + ';');
            }
        }
        return buffer.join('');
    }
    

    ECMAScript ≤ 5, without Emoji support:

    function decimalEscape(s) {
        var buffer = [];
        for(var i = 0, f = s.length; i < f; ++i) {
            if(s.charCodeAt(i) <= 127) {
                buffer.push(s.charAt(i));
            } else {
                buffer.push('&#' + s.charCodeAt(i) + ';');
            }
        }
        return buffer.join('');
    }
    

    Usage:

    decimalEscape("Olá"); // -> returns "Ol&#225;"
    

    If you don't have a proper JavaScript string yet (just a bunch of bytes in some kind of buffer or if the string you have is already in the wrong encoding), you will have to fix the string first, of course.