2017-03-04 11 views
0

与えられた配列を持っている場合、与えられたスペースのテキストを正当化する方法はありますか?すべてのインデックスに空白を含む20文字が必要です。配列のインデックス内のテキストを均等化する

アレイの例

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

と、結果は

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

がどのようにこの最初の配列は以下のようにフォーマットを取得するために行うことができます(この例では20)、所定の長さに正当化されるだろう二番目?

+0

あなたは、配列を1秒のようにフォーマットされている場合、あなたが見つけるだろうか、意味ですか? –

+0

最初のような通常の配列が与えられたときには、文の通常の構造があり、次にそれを2番目のようにフォーマットする必要があります。 – 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));

関連する問題