こうこく
作 ▸

JavaScript 文字のパディング (右埋め・左埋め・中央寄せ)

String.repeat() がES6なのでIE11では動きまてん

右埋め
const padRight = (str, padchar, len) => {
  const padstr = padchar.repeat(len);
  return `${str}${padstr}`.slice(0, len);
};
左埋め
const padLeft = (str, padchar, len) => {
  const padstr = padchar.repeat(len);
  return `${padstr}${str}`.slice(-len);
};
中央寄せ
const padSide = (str, padchar, len) => {
  const lPadstr = padchar.repeat(Math.floor(len / 2));
  const rPadstr = padchar.repeat(Math.ceil(len / 2));
  const padded = `${lPadstr}${str}${rPadstr}`;
  const start = Math.floor((padded.length - len) / 2);
  return padded.slice(start, start + len);
};