Created
June 8, 2020 04:57
-
-
Save ruter/9f16249b1e1535dd114a075e015ebf77 to your computer and use it in GitHub Desktop.
字符数计算,包含 CJK 字符
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
var pattern = /[a-zA-Z0-9_\u0392-\u03c9\u00c0-\u00ff\u0600-\u06ff\u0400-\u04ff]+|[\u4e00-\u9fff\u3400-\u4dbf\uf900-\ufaff\u3040-\u309f\uac00-\ud7af]+/g; | |
function wordCount(str) { | |
var m = str.match(pattern); | |
var count = 0; | |
if (!m) { | |
return 0; | |
} | |
for (var i = 0; i < m.length; i++) { | |
if (m[i].charCodeAt(0) >= 0x4e00) { | |
count += m[i].length; | |
} else { | |
count += 1; | |
} | |
} | |
return count; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment