使用JavaScript的字符串填充中心[关闭]

问题描述 投票:-4回答:1

我有一个带换行符的字符串:

character = 'ABC\nDEFGHI\nJKLMNOPQ'

我想做中心垫,左右两侧都有空格。

有可能吗?我需要它在pos打印机中打印标题信息。

Desired output:

       ABC
      DEFGHI
     JKLMNOPQ

我该如何解决这个问题?

javascript center pad
1个回答
2
投票

你可以

  • 拆分字符串
  • 获得所有部件的最大长度
  • 垫以半长开始,垫端以最大长度开始。

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'));
© www.soinside.com 2019 - 2024. All rights reserved.