All files / str sizeOfUTF8String.ts

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

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 23 24 25 26                    1x 2x 2x 2x     7x   2x     2x     1x  
/**
 * 取字符串 utf8 编码长度
 * @method sizeOfUTF8String
 * @param {String} str
 * @return {Number} 字符串长度
 * @example
 * import { sizeOfUTF8String } from '@spore-ui/tskit';
 * sizeOfUTF8String('中文c'); //return 7
*/
 
export function sizeOfUTF8String(str: string): number {
  const len = str.length;
  let reLen = 0;
  for (let i = 0; i < len; i += 1) {
    if (str.charCodeAt(i) < 27 || str.charCodeAt(i) > 126) {
      // 全角
      reLen += 2;
    } else {
      reLen += 1;
    }
  }
  return reLen;
}
 
export default sizeOfUTF8String;