繁体   English   中英

对齐数组索引中的文本

[英]Justifying text in the indexes of an array

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

示例数组

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

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

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

您如何执行此操作以使第一个数组的格式与第二个数组相同?

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

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

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

然后,这只是一个计数问题。 计算单词和字符,找出应该有多少空格,并在空格数量不均匀等情况下添加一些内容以填充最后一个空格。

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM