Maison >interface Web >js tutoriel >js, 截取字符串长度, 字符串, 长度 js截取字符串长度(中、英)
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()+'......');
}
});
}