All files / str getLeftByteString.ts

87.5% Statements 7/8
50% Branches 1/2
100% Functions 1/1
87.5% Lines 7/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 27 28 29 30                          1x   1x 6x   6x     6x       6x     1x  
/* eslint-disable no-control-regex */
/**
 * 从左到右取字符串,中文算两个字符
 * @method getLeftByteString
 * @param {String} str
 * @param {Number} lens
 * @return {String} str
 * @example
 * import { getLeftByteString } from '@spore-ui/tskit';
 * //向汉编致敬
 * getLeftByteString('世界真和谐', 6); // '世界真'
*/
 
import { byteLength } from './byteLength';
 
export function getLeftByteString(str: string, lens: number): string {
  const proxyStr = str.replace(/\*/g, ' ')
    .replace(/[^\x00-\xff]/g, '**');
  const proxyLength = proxyStr.slice(0, lens)
    .replace(/\*\*/g, ' ')
    .replace(/\*/g, '').length;
  let rs = str.slice(0, proxyLength);
  if (byteLength(rs) > lens && lens > 0) {
    rs = rs.slice(0, rs.length - 1);
  }
  return rs;
}
 
export default getLeftByteString;