在数组的索引中对齐文本

时间:2017-03-04 20:40:04

标签: javascript arrays

如果你有给定的数组,你会如何证明给定空间的文本?假设您需要20个字符,包括每个索引中的空格。

示例数组

['Hello there champ', 
 'example text', 
 'one two three'
]

然后结果将证明给定长度(本例中为20)

['Hello  there   champ', 
 'example         text', 
 'one    two     three'
]

如何才能将第一个数组格式化为第二个?

3 个答案:

答案 0 :(得分:0)

您可以拆分字符串并添加到除最后一个项目之外的所有项目,直到达到所需长度为止。

var array = ['Hello there champ', 'example text', 'one two three'],
    length = 20;

array.forEach(function (a, i, aa) {
    var temp = a.split(' '),
        l = length - temp.join('').length;
    while (l) {
        temp.every(function (b, j, bb) {
            if (j + 1 === bb.length) {
                return;
            }
            if (l) {
                bb[j] += ' ';
                l--;
                return true;
            }
        });
    }
    aa[i] = temp.join('');
});

console.log(array);

答案 1 :(得分:0)

将其拆分为单独的动作,首先将数组映射回来,然后拆分字边界并修剪已存在的空格。

然后它只是一个计数问题。计算单词和字符,计算出应该有多少空格,并添加一些东西以填充最后一个空格,当有不均匀的空格数等时。



var arr = [
    'Hello there champ',
    'example text',
    'one two three'
]

function justify(a, n) {
    return a.map( x => {
    	var words  = x.split(/\b/).filter( y => y.trim().length)
        var total  = words.join('').length;
        var spaces = (n - total) / (words.length - 1);
        var fill   = new Array(Math.floor(spaces) + 1).join(" ");
        var result = words.join( fill );
        return result.length === n ? result : result.replace(/\s([^\s]*)$/, "  $1");
    });
}

console.log( justify(arr, 20) );




答案 2 :(得分:0)

我们的想法是确定需要多少空格,并将它们平均分配给现有的空白(单词之间的空格)。

var arr = ['Hello there champ', 'example text', 'one two three'];

var newArr = [];

arr.forEach(v => {
    var words = v.split(/\s+/);
    var needed = 20 - words.join("").length;
    var gaps = words.length - 1;
    var perGap = Math.floor(needed / gaps);
    var extra = needed - (perGap * gaps);
    var newValue = words.join(Array(perGap + 1).join(" "));
    if(extra){ // add the extra needed spaces in the last gap
        newValue = newValue.replace(new RegExp(words[words.length - 1]+"$"), Array(extra + 1).join(" ") + words[words.length - 1]);
    }
    newArr.push(newValue);
});
newArr.forEach(v => console.log(v));

相关问题