You cannot count on "characters" here. According to the SMS article on Wikipedia, SMS uses one of three different encodings (7-bit GSM, 8-bit GSM and UTF-16). So first you need to know / decide which encoding you will use.
If you know that you will always use UTF-16, then you can calculate the number of 16-bit code units that the string will be in. Standard SMS can consist of 70 16-bit code blocks. But this will limit the messages in Latin letters to 70. Therefore, if you want to use the full 160 characters (with 7-bit encoding) or 140 characters (with 8-bit encoding) for Latin characters, you will need to distinguish between three cases.
Example for counting 16-bit UTF-16 code blocks:
var message = "您好,請問你吃飯了嗎?"; var utf16codeUnits = 0; for (var i = 0, len = message.length; i < len; i++) { utf16codeUnits += message.charCodeAt(i) < 0x10000 ? 1 : 2; }
By the way, this one will come up with the same amount as you as “wrong”, so you will need to explain why you think they are wrong.
EDIT
Despite the fact that I have already been accepted, I quickly hacked a function that correctly (as far as I can tell) calculates 7-bit (if possible) GSM signals and UTF-16 SMS messages: http://jsfiddle.net/puKJb /
source share