UNPKG

989 BJavaScriptView Raw
1/**
2 * 生成居中对齐的字符串,主要方法是将 left 字符串调整成固定长度
3 *
4 * @param {String} center 中间位置的字串
5 * @param {String} left 左边位置的字串
6 * @param {String} right 右边位置的字串
7 * @param {Number} leftLen 左边字符串默认长度,不足以空格补足
8 * @return {String} 拼接的字符串
9 */
10exports.center = (center, left, right, leftLen = 17) => {
11 const REPLACER = '...'; // 用于替换多余字符的字串
12
13 if (leftLen < REPLACER.length) {
14 return `${REPLACER} ${center} ${right}`;
15 }
16
17 // 左边比边界还长的,格式化长度并设最后的三个字符为 ...
18 if (left.length > leftLen) {
19 left.length = leftLen;
20 left = left.split('').slice(0, leftLen - REPLACER.length).concat(REPLACER).join('');
21 }
22
23 // 生成左字符串的补足字串
24 let delta = leftLen - left.length;
25 let addon = '';
26 while (delta--) {
27 addon += ' ';
28 }
29
30 return `${addon}${left} ${center} ${right}`;
31};