Last active
September 18, 2019 02:29
-
-
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.
This file contains 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
/** | |
* 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