Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
41
rated 0 times [  46] [ 5]  / answers: 1 / hits: 165416  / 15 Years ago, mon, february 8, 2010, 12:00:00

I have a javascript string which is about 500K when being sent from the server in UTF-8. How can I tell its size in JavaScript?



I know that JavaScript uses UCS-2, so does that mean 2 bytes per character. However, does it depend on the JavaScript implementation? Or on the page encoding or maybe content-type?


More From » string

 Answers
21

You can use the Blob to get the string size in bytes.



Examples:





console.info(
new Blob(['😂']).size, // 4
new Blob(['👍']).size, // 4
new Blob(['😂👍']).size, // 8
new Blob(['👍😂']).size, // 8
new Blob(['I'm a string']).size, // 12

// from Premasagar correction of Lauri's answer for
// strings containing lone characters in the surrogate pair range:
// https://stackoverflow.com/a/39488643/6225838
new Blob([String.fromCharCode(55555)]).size, // 3
new Blob([String.fromCharCode(55555, 57000)]).size // 4 (not 6)
);




[#97640] Thursday, February 4, 2010, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kadinl

Total Points: 321
Total Questions: 117
Total Answers: 103

Location: Nepal
Member since Mon, Jan 4, 2021
3 Years ago
;