簡體   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