Pad string

JavaScript, String · Oct 22, 2020

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

  • Pad number

    Pads a given number to the specified length.

    JavaScript, String · Oct 3, 2020

  • Random alphanumeric string

    Generates a random string with the specified length.

    JavaScript, String · Oct 22, 2020

  • Mask a value

    Replaces all but the last num of characters with the specified mask character.

    JavaScript, String · Oct 21, 2020