Last active
December 13, 2015 21:18
-
-
Save h2non/4976332 to your computer and use it in GitHub Desktop.
Simple UTF8 string bytes counter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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