Does anyone knows how to check the number of byte for a string? In my case, the maximun size of character in db is 255 and i have tried to check the length of character myString.length. Unfortunately, user sometimes input chinese character and make the size is larger than that of database column(one chinese character represent 2 bytes). So, i would like to know how to check the number of byte for a string. If u have another methods to deal with this problem, it is welcome to reply. Thank a lot.
I will suggest something like this: function getNumBytes(s) { var numBytes=0; for (var i=0; i<s.length; i++) { var code=s.charCodeAt(i); if (code < 0x0100) { numBytes+=1; // single byte } else { numBytes+=2; // double byte } } return numBytes; } Code (markup): Get number of bytes by getNumBytes(myString). I hope its helpful.
I am sincerely thanks to you. This solution is very useful for me to deal with a problem. Besides, i would like to know any document does describe what wording of 0x100 or what codeChartAt(another control character) such as codeChartAt(enter). Thanks
Chect out ascii tables http://www.lookuptables.com/ Also, Enter: "\r".charCodeAt(0): 0x0013 New Line: "\n".charCodeAt(0): 0x0010 Tab: "\t".charCodeAt(0): 0x0009 Backspace: "\b".charCodeAt(0): 0x0008
For the control character, the charCodeAt(i) this character is lesser than 0x0100. Based on the previous check bytes algorithm, lesser than 0x0100 will be counted to 2 bytes. Is it correct for counting control character to be 2 bytes by using with charCodeAt method.