Skip to content

Home

Pad string

Pads a string on both sides with the specified character, if it's shorter than the specified length.

const pad = (str, length, char = ' ') =>
  str.padStart((str.length + length) / 2, char).padEnd(length, char);

pad('cat', 8); // '  cat   '
pad(String(42), 6, '0'); // '004200'
pad('foobar', 3); // 'foobar'

More like this

Start typing a keyphrase to see matching snippets.