中英文字符的字符串长度校验

/**
* 得到字符串的字符长度(一个汉字占两个字符长)
*/
function getBytesLength(str) {
// 在GBK编码里,除了ASCII字符,其它都占两个字符宽
return str.replace(/[^x00-xff]/g, 'xx').length;
}

/**
* 根据字符长来截取字符串
*/
function subStringByBytes(val, maxBytesLen) {
var len = maxBytesLen;
var result = val.slice(0, len);
while(getBytesLength(result) > maxBytesLen) {
result = result.slice(0, --len);
}
return result;
}
posted @ 2009-02-25 09:41  亦续缘  阅读(322)  评论(0编辑  收藏  举报