Snippets

代码片段收集板

按字节截取字符串edit

日期:

作者: 小胡子哥

Author: 吕大豹 Email: 670818517(at)qq.com

按字节截取字符串,使用示例:subSt(‘我是中国人’, 4); //我是

function subSt(str, len){
  var newLength = 0;
  var newStr = "";
  var chineseRegex = /[^\x00-\xff]/g;
  var singleChar = "";
  var strLength = str.replace(chineseRegex,"**").length;
  for(var i = 0;i < strLength;i++) {
      singleChar = str.charAt(i).toString();
      if(singleChar.match(chineseRegex) != null) {
          newLength += 2;
      } else  {
          newLength++;
      }
      if(newLength > len) {
          break;
      }
      newStr += singleChar;
  }
  return newStr;
}
标签:

loading...

这网速真是弱爆了...客官稍等,评论还在加载~