欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  web前端

js, 截取字符串长度, 字符串, 长度 js截取字符串长度(中、英)

程序员文章站 2022-05-09 15:30:39
...
js 截取字符串长度,截取时中文按2个字节计算

function worldLimit(className,factLength){

$('.'+className).each(function(){
var content = $(this).text();
var allLength = 0;
for (var i = 0; i < content.length; i++) {
var c = content.charCodeAt(i);
//单字节加1
if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
allLength++;
}
else {
allLength += 2;
}
}
if(allLength > factLength){
var subContent = '';
var subLength = 0;
var factLength = 0;
for (var i = 0; i < content.length; i++) {
var c = content.charCodeAt(i);
//单字节加1
if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
subLength++;
}
else {
subLength += 2;
}
factLength ++;
if(subLength > factLength){
break;
}else{
subContent = content.substring(0,factLength);
}
}
$(this).text(subContent);
$(this).html($(this).html()+'......');
}
});

}