Quantcast
Channel: String length in bytes in JavaScript - Stack Overflow
Viewing all articles
Browse latest Browse all 19

String length in bytes in JavaScript

$
0
0

In my JavaScript code I need to compose a message to server in this format:

<size in bytes>CRLF<data>CRLF

Example:

3foo

The data may contain unicode characters. I need to send them as UTF-8.

I'm looking for the most cross-browser way to calculate the length of the string in bytes in JavaScript.

I've tried this to compose my payload:

return unescape(encodeURIComponent(str)).length +"\n"+ str +"\n"

But it does not give me accurate results for the older browsers (or, maybe the strings in those browsers in UTF-16?).

Any clues?

Update:

Example: length in bytes of the string ЭЭХ! Naïve? in UTF-8 is 15 bytes, but some browsers report 23 bytes instead.


Viewing all articles
Browse latest Browse all 19

Trending Articles