Created
November 11, 2015 01:04
-
-
Save laispace/b6b12df3145205df8873 to your computer and use it in GitHub Desktop.
计算字符串长度, 中文算两个
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
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
为什么有一个94呢