- /**
- * 安字节截取UTF8字符长度
- * 使用方法
- * var str = "helloworld";
- * str = str.subBtyesString(5);
- * @param length
- * @return {String}
- * @auth opmetic@gmail.com
- */
- String.prototype.subBtyesString = function (length) {
- var tStr = ""; //返回的字符串
- var pEnd = 0; //截取字符串的结束位置
- var totalLength = 0; //
- var charCode;
- for (var i = 0; i < this.length; i++) {
- charCode = this.charCodeAt(i);
- if (charCode < 0x007f) {
- totalLength++;
- }
- else { //当为非字母时, 按第个字符占两个字节宽度计算
- totalLength += 2;
- }
- if (totalLength <= length) {
- pEnd = i + 1;
- }
- }
- if (pEnd < this.length) { //有截取
- tStr = this.substr(0, pEnd);
- tStr += "...";
- }
- else { //没有截取
- tStr = this.substr(0, this.length);
- }
- return tStr;
- }
- //该片段来自于http://www.codesnippet.cn/detail/190820135214.html
来源: http://www.codesnippet.cn/detail/190820135214.html