以字节为单位计算文本长度 [英] Calculate the length of text in bytes

查看:143
本文介绍了以字节为单位计算文本长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述




我需要在文本

输入中计算文本的物理长度。术语物理的是指物理的。在这种情况下,我认为
将7bit-Ascii视为每个字符一个字节。其他字符

可能更长,例如西里尔字母每个字符2个字节。


有没有一种安全简便的方法来注意非7bit-Ascii输入?


干杯,


M.


-

对复杂的乐趣感兴趣?你,老公,女朋友。

越多越好。与Kirby取得联系,仅通过WASTE,Box 7391,LA

- = - = - - = - = - = - = - - = - = -

Martin Dietze - = - = - http://www.the-little -red-haired-girl.org

推荐答案

Martin Herbert Dietze写道:
Martin Herbert Dietze wrote:


我需要在文本输入中计算文本的物理长度。术语物理的是指物理的。在这种情况下,我将7bit-Ascii视为每个字符一个字节。其他角色可能会更长,例如西里尔字母每个字符2个字节。

有没有一种安全简便的方法来注意非7bit-Ascii输入?
Hi,

I need to calculate the physical length of text in a text
input. The term "physical" means in this context, that I
consider 7bit-Ascii as one-byte-per character. Other characters
may be longer, e.g. cyrillic would be 2 bytes per character.

Is there a safe and easy way to notice non-7bit-Ascii input?




有这里有两个问题。第一个是unicode

个字符(代码点)的数量。第二个是否有任何unicode

字符需要超过7位才能代表。


函数charCount(str){

//计算unicode字符的数量,这可能与

str.length

var esc = escape(str); //逃避比encodeURI更强大

返回esc.replace(/%uD [CF] ../ g,'''')

.replace(/%u .... / g,''"'')

.replace(/%../ g,"''")

.length;

}


函数SevenBitsOrLess(str){

//如果str包含需要8或
更多位

var esc = escape(str);

如果(esc.match(/%u /))返回false;

返回(!esc.match(/%[89A-F] /));

}


//示例

var str0 =" ab



There are two questions here. The first is the number of unicode
characters (code points). The second is whether there are any unicode
characters requiring more than 7 bits to represent.

function charCount(str) {
// counts the number of unicode characters, which may differ from
str.length
var esc = escape(str); // escape more robust than encodeURI
return esc.replace(/%uD[C-F]../g,'''')
.replace(/%u..../g,''"'')
.replace(/%../g,"''")
.length;
}

function SevenBitsOrLess(str) {
// returns false if str includes a unicode character requiring 8 or
more bits
var esc = escape(str);
if (esc.match(/%u/)) return false;
return (!esc.match(/%[89A-F]/));
}

// Example
var str0 = "ab


1 _ ^%25


。%D8%B7%EA%96%A4,% F3%87%BB%81"

str = decodeURI(str0);

alert(charCount(str));


请注意,在示例中,

str0.length => 40

str.length => 15

alert(charCount(str))=> 14

来自维也纳的Csaba Gabor

.%D8%B7 %EA%96%A4,%F3%87%BB%81";
str = decodeURI (str0);
alert (charCount(str));

Note that in the example,
str0.length => 40
str.length => 15
alert (charCount(str)) => 14

Csaba Gabor from Vienna


这篇关于以字节为单位计算文本长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆