In my JavaScript code I need to compose a message to server in this format:
<size in bytes>CRLF
<data>CRLF
Example:
3
foo
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 + "
" + str + "
"
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.
Question&Answers:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…