Skip to content

Instantly share code, notes, and snippets.

@Alex1990
Last active September 18, 2019 02:29
Show Gist options
  • Save Alex1990/306422612ede27235c73 to your computer and use it in GitHub Desktop.
Save Alex1990/306422612ede27235c73 to your computer and use it in GitHub Desktop.
Count a string(mixing English and Chinese characters) length, and this is a rough function.
/**
* Description: Count a string (mixing English and Chinese characters) length.
* A basic and rough function.
*
* Performance:
* Multiple methods performance test on http://jsperf.com/count-string-length.
* You can see that using regexp to check range is very slow from the above test page.
*/
function strLen(str) {
var count = 0;
for (var i = 0, len = str.length; i < len; i++) {
count += str.charCodeAt(i) < 256 ? 1 : 2;
}
return count;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment