JavaScript实现的GBK、UTF8字符串实际长度计算函数_基础知识

WBOY
Release: 2016-05-16 16:38:33
Original
1973 people have browsed it

大家都知道,在JS中字符串的长度不分中英文字符, 每一个字符都算一个长度,这跟PHP里的strlen()函数就不太一样。PHP里的strlen()函数根据字符集把GBK的中文每个2累加,把UTF-8的中文字符每个按3累加。

有些童鞋可能要问了,为什么要计算实际长度?

主要是为了匹配数据库的长度范围内,比如GBK的数据库某字段是varchar(10),那么就相当于5个汉字长度,一个汉字等于两个字母长度。如果是UTF8的数据库则是每个汉字长度为3。

知道了以上原理以后,我们就可以算出一个字符串的实际长度了,如果是GBK字符集遇到中文加2,如果是UTF8字符集遇到中文加3即可
GBK长度计算函数:

复制代码代码如下:

// GBK字符集实际长度计算
function getStrLeng(str){
var realLength = 0;
var len = str.length;
var charCode = -1;
for(var i = 0; i charCode = str.charCodeAt(i);
if (charCode >= 0 && charCode realLength += 1;
}else{
// 如果是中文则长度加2
realLength += 2;
}
}
return realLength;
}

UTF8长度计算函数:
复制代码代码如下:

// UTF8字符集实际长度计算
function getStrLeng(str){
var realLength = 0;
var len = str.length;
var charCode = -1;
for(var i = 0; i charCode = str.charCodeAt(i);
if (charCode >= 0 && charCode realLength += 1;
}else{
// 如果是中文则长度加3
realLength += 3;
}
}
return realLength;
}
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!