Skip to content

Instantly share code, notes, and snippets.

@h2non
Last active December 13, 2015 21:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save h2non/4976332 to your computer and use it in GitHub Desktop.
Save h2non/4976332 to your computer and use it in GitHub Desktop.
Simple UTF8 string bytes counter
/**
* Simple UTF8 String bytes counter
* @author Tomas Aparicio
* @license MIT
* @param {String} str String to count
* @return {Number} Bytes
* @method bytesCounter
*/
function bytesCounter(str){
var code, i, bytes = 0;
for (i=0;i<str.length;i+=1) {
code = str.charCodeAt(i);
if (code < 129) {
bytes += 1;
} else if (code < 2049) {
bytes += 2;
} else {
bytes += 3;
}
}
return bytes;
}
// test
console.log(bytesCounter('@ sámplE $tRinG| ª&%_.^·~)(= ?¿[-]'));
console.log(bytesCounter('华语/華語 普通话'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment