All files / str byteLength.ts

100% Statements 6/6
100% Branches 2/2
100% Functions 1/1
100% Lines 6/6

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22                      1x 9x   1x   8x 8x     1x  
/* eslint-disable no-control-regex */
/**
 * 获取字符串长度,一个中文算2个字符
 * @method byteLength
 * @param {String} str 要计算长度的字符串
 * @return {Number} 字符串长度
 * @example
 * import { byteLength } from '@spore-ui/tskit';
 * byteLength('中文cc'); // 6
 */
 
export function byteLength(str: string): number {
  let aMatch = null;
  if (!str) {
    return 0;
  }
  aMatch = str.match(/[^\x00-\xff]/g);
  return (str.length + (!aMatch ? 0 : aMatch.length));
}
 
export default byteLength;