Skip to content

Instantly share code, notes, and snippets.

@mingyun
Created January 8, 2014 12:37
Show Gist options
  • Save mingyun/8316191 to your computer and use it in GitHub Desktop.
Save mingyun/8316191 to your computer and use it in GitHub Desktop.
按字节截取字符串
baidu.string.getByteLength = function(source) {
return String(source).replace(/[^\x00-\xff]/g, "ci").length;
};
/*
* Tangram
* Copyright 2009 Baidu Inc. All rights reserved.
*
* path: baidu/string/subByte.js
* author: dron, erik
* version: 1.1.0
* date: 2009/11/30
*/
/**
* 对目标字符串按gbk编码截取字节长度
*
* @param {string} source 目标字符串
* @param {number} length 需要截取的字节长度
* @return {string} 字符串截取结果
*/
baidu.string.subByte = function(source, length) {
source = String(source);
var getLen = baidu.string.getByteLength,
i, len, current, next, currentLen, nextLen;
if (length < 0 || getLen(source) <= length) {
return source;
}
len = source.length;
for (i = Math.floor(length / 2) - 1; i < len; i++) {
current = next || source.substr(0, i);
currentLen = nextLen || getLen(current);
if (currentLen == length) {
return current;
} else {
next = source.substr(0, i + 1);
nextLen = getLen(next);
if (nextLen > length) {
return current;
}
}
}
return source;
};
这种方式的实现原理是先将中文替换成中文加个空格,这样变相的将一个中文变成了2个字节,然后在这个基础上截取,截取完成后在将中文加空格变成中文。
baidu.string.subByte1 = function(source, length) {
return (source + '').substr(0, length).replace(/([^\x00-\xff])/g, '$1 ').substr(0, length).replace(/([^\x00-\xff]) /g, '$1');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment