Search code examples
javascriptgoogle-chromefirefoxuint8array

Uint8Array to string conversion difference between Firefox and Chromium


I'm trying to convert binary data to string like this:

var string = new TextDecoder("utf-8").decode(Uint8Array.from([1, 2, 3]));

When I look for what variable string returns in Firefox, it shows expected string "\u0001\u0002\u0003"

Although when I do the same in Chrome, string returns an empty string ""

Can someone, please, explain, what's going on?


Solution

  • Chrome console renders unprintable characters differently than firefox. Specifically, unprintable characters are rendered as the empty square. Nonetheless the string consists of the proper unicode code points.

    The following one-liner (well ...) creates the \u... rendering.

    Array.from(
        {length: string.length}
      , (v, k) => k
    )
       .map ( idx => `\\u${string.codePointAt(idx).toString(16).padStart(4, '0')}`)
       .join()
    ;
    

    Test it:

    let string = new TextDecoder("utf-8").decode(Uint8Array.from([1, 2, 3]));
    
    console.log(`raw rep: '${string}'.`);
    console.log(`code point rep: '${Array.from(
        {length: string.length}
      , (v, k) => k).map ( idx => `\\u${string.codePointAt(idx).toString(16).padStart(4, '0')}` 
    ).join("")}'.`);