使用javascript计算textarea中的字节数 [英] Count bytes in textarea using javascript
问题描述
我需要计算使用javascript编码UTF8时textarea的字节长度。知道怎么做吗?
I need to count how long in bytes a textarea is when UTF8 encoded using javascript. Any idea how I would do this?
谢谢!
推荐答案
编辑:正如didier-l所指出的,此函数不能正确计算代理字符。
edit: as didier-l has pointed out, this function does not count surrogate characters correctly.
broofa的答案应该正确计算代理人数,请参阅 https://stackoverflow.com / a / 12206089/274483 。
broofa's answer should count surrogates properly, see https://stackoverflow.com/a/12206089/274483.
我在这里测试了两个提议版本以及一个天真的实现:
I have tested the two proposed versions here as well as a naive implementation:
getUTF8Length: function(string) {
var utf8length = 0;
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utf8length++;
}
else if((c > 127) && (c < 2048)) {
utf8length = utf8length+2;
}
else {
utf8length = utf8length+3;
}
}
return utf8length;
}
结果是我的版本在firefox中稍快一点,在chrome中明显加快(~30x)比这里发布的版本。
With the result that my version is slightly faster in firefox and significantly faster in chrome (~30x) than the here posted versions.
这篇关于使用javascript计算textarea中的字节数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!