0

Letter ł (l with tail) is represented in Unicode as U+0142, hex: xc5 x82, decimal: 197 130.

I have an array in JavaScript:

var b = [197, 130]; 

How to make string ł from it?

I tried this on JSFiddle:

var s;
s = String.fromCharCode(b[0], b[1]);

But then s is equal to Å (A with something on top).
I also tried other methods in the fiddle, but I can't get the correct result.

3 Answers 3

1

hex: xc5 x82

That's the UTF-8 byte encoding of ł.

s = String.fromCharCode(b[0], b[1]);

That's interpreting each byte as a single character, which is effectively decoding the bytes using the ISO-8859-1 encoding, because this encoding happens to share the same numbers as the first 256 characters of Unicode.

There is a neat JavaScript trick to turn a string where each character stands in for the byte of the same number, into a UTF-8 decoded string: send it through the legacy escape() builtin function, which is a broken URL-encoder, and then decode it using the real URL-decoder, decodeURIComponent.

So for any Array of UTF-8 bytes you can get the decoded Unicode String by doing:

function utf8BytesToString(b) {
    return decodeURIComponent(escape(String.fromCharCode.apply(null, b)));
}

utf8BytesToString([0xc5, 0x82]) // "ł"
Sign up to request clarification or add additional context in comments.

Comments

0

For two byte sequences you need to use mask 110xxxxx 10xxxxxx, which refers to:

var bytes = [0xc5, 0x82];  // [197, 130]

String.fromCharCode(((bytes[0] & 0x1f) << 6) | (bytes[1] & 0x3f));  // "ł"

Comments

0

You're probably after String.fromCodePoint:

String.fromCodePoint(128105, 8205, 128188) // 👩‍💼

// or if you have the hex values, parse them first:
String.fromCodePoint(parseInt("1F469", 16), parseInt("200D", 16), parseInt("1F4BC", 16)) // 👩‍💼

// for arbitrary numbers of points, use JS spread notation:
let codePoints = [128105, 8205, 128188];
String.fromCodePoint(...codePoints)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.