Search code examples
javascriptpaddingcenter

String pad center using JavaScript


I have a string with newlines:

character = 'ABC\nDEFGHI\nJKLMNOPQ'

I want to do center pad, both of left and right sides having blank spaces.

Is it possible to do this? I need it to print header information in a POS printer.

Desired output:

       ABC
      DEFGHI
     JKLMNOPQ

How do I solve this problem?


Solution

  • You could

    • split the string
    • get the max length of all parts
    • pad start with the half length and pad end with the max length.

    var string = 'ABC\nDEFGHI\nJKLMNOPQ',
        parts = string.split('\n'),
        max = Math.max(...parts.map(({ length }) => length));
    
    parts = parts.map(s => s
        .padStart(s.length + Math.floor((max - s.length) / 2), ' ')
        .padEnd(max, ' ')
    );
    
    console.log(parts.join('\n'));