2017-03-04 30 views
0

如果您有给定的数组,那么您将如何确定给定空间的文本?假设你需要20个字符,包括每个索引中的空格。对数组索引中的文本进行调整

例阵列

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

,然后将结果是合理的给定长度(20本示例)

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

你怎么能做到这一点,以获得第一阵列格式应第二?

+0

你的意思是,你怎么会发现,如果一个数组的格式如下第二个? –

+0

当我得到一个像第一个正常的数组时,正常的句子结构,然后我需要将它格式化为第二个格式 – Chipe

+0

只需确定需要多少空间并将其等量添加到现有空间。 – Titus

回答

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);

0

拆分它来单独行动,第一阵列映射回,然后分裂在字边界和修剪掉那些已经存在的空间。

然后这只是一个计数问题。算的话和人物,弄清楚应该有多少空间会有,并添加东西来填补在过去的空间,当有空格等

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

 
function justify(a, n) { 
 
    return a.map(x => { 
 
    \t 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));

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));