首页 > 代码库 > 按字节截取字符串

按字节截取字符串

按字节截取字符串,参数:字符串,截取的字符          function getStr(str, n) {                 if (lenFor(str) <= n) {                     return str;                 }                 var tmpStr = str.substr(0, n);                 var tmpCode = tmpStr.replace(/[^\x00-\xff]/g, ‘\r\n‘).split(‘‘);                 n = (tmpCode[n - 1] == ‘\r‘) ? n - 2 : n - 1;                 var l = tmpCode.slice(0, n).join(‘‘).replace(/\r\n/g, ‘*‘).length + 1;                 return tmpStr.substr(0, l)+"...";             };

            function lenFor(str) {                 var byteLen = 0, len = str.length;                 if (str) {                     for (var i = 0; i < len; i++) {                         if (str.charCodeAt(i) > 255) {                             byteLen += 2;                         }                         else {                             byteLen++;                         }                     }                     return byteLen;                 }                 else {                     return 0;                 }             }