原文地址:http://sozai.wlling.com/html/Tutorial/JavaScript/2009/0214/2936.html

/**

* 得到字符串的字符长度(一个汉字占两个字符长)

*/

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;

}

相关文章:

  • 2022-12-23
  • 2021-11-05
  • 2022-12-23
  • 2022-12-23
  • 2021-08-31
  • 2021-08-23
猜你喜欢
  • 2022-12-23
  • 2022-03-04
  • 2021-12-19
  • 2022-12-23
  • 2022-02-06
  • 2021-08-13
  • 2022-12-23
相关资源
相似解决方案