2017-03-04 43 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));