-1

Heading1 Heading2 FoooBar 23 FoBar 5 FooooBar 12

In above example, I want the numbers 23 5 and 12 always to be in a line irrespective of the length of first column values. The values in second column should be aligned. How do I do this in Javascript?

I solved this like

function pad(pad, str, padRight) {
let difference = pad - str.length;
let exactTab = Math.ceil(difference / 4);
console.log(exactTab);
  if (typeof str === 'undefined') 
    return pad;
  if (padRight) {
    return Array(exactTab).join('\t');
  } else {
    return (str + difference).substring(0, pad.length);
  }
}
Nick
  • 135
  • 1
  • 2
  • 10
  • 5
    Possible duplicate of [Is there a JavaScript function that can pad a string to get to a determined length?](http://stackoverflow.com/questions/2686855/is-there-a-javascript-function-that-can-pad-a-string-to-get-to-a-determined-leng) – XCS Aug 02 '16 at 13:28
  • @Cristy this is not a duplicate of the question you mentioned in the link – Nick Aug 02 '16 at 13:42
  • Your question is the same, but phrased differently. You ask how can you add right padding to a string so it is always the same length. So, if you know that you have to use padding now, how can you solve your problem? This is another question, but it's pretty easy to figure out the solution. – XCS Aug 02 '16 at 14:03
  • You are probably right, can solve it with that. – Arathi Sreekumar Aug 02 '16 at 14:05
  • thanks @Cristy for your inputs. – Nick Aug 02 '16 at 14:24

1 Answers1

1

Well the steps involved would be:

  1. Decide the position at which you want the second column to start (eg: find the length of the longest item in first column and add x, eg: say 'FooooBar' is your longest word (length = 8), then say you want a gap of 5, then the position of the second column will be at 13 (length + gap).

  2. Make all of first column to have a right padding to be of length computed above. Use the right padding logic provided in solutions at Is there a JavaScript function that can pad a string to get to a determined length?

And you have your result.

Community
  • 1
  • 1
Arathi Sreekumar
  • 2,544
  • 1
  • 17
  • 28