Skip to content

Instantly share code, notes, and snippets.

@paddingme
Forked from Alex1990/strLen.js
Created May 10, 2019 07:11
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 paddingme/276111f6d6e704da7ae6323240c676ea to your computer and use it in GitHub Desktop.
Save paddingme/276111f6d6e704da7ae6323240c676ea 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