Skip to content

Instantly share code, notes, and snippets.

@laispace
Created November 11, 2015 01:04
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 laispace/b6b12df3145205df8873 to your computer and use it in GitHub Desktop.
Save laispace/b6b12df3145205df8873 to your computer and use it in GitHub Desktop.
计算字符串长度, 中文算两个
function countStringLength (string) {
var len = string.length;
var count = 0;
for (var i = 0; i < len; i ++) {
var num = string.charCodeAt(i);
if (num == 94 || num > 127) {
count += 2;
} else {
count += 1;
}
}
return count;
}
countStringLength('abc'); // => 3
countStringLength('abc啊'); // => 5
@newpost
Copy link

newpost commented Dec 27, 2019

为什么有一个94呢

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment