Design & Download
Your JS Library
in Seconds!!!

Snippet: String Padding - ES7 Style

Written by Christopher West (cwest) on December 05, 2015.
Pads a string make sure that it is always at least a specific length.
function padStart(str, maxLength, opt_fillString) {
  str += '';

  var filler, fillLen, stringLength = str.length;

  return maxLength > stringLength
    ? (
        filler = (opt_fillString !== undefined ? opt_fillString + '' : '') || ' ',
        fillLen = maxLength - stringLength,
        (new Array(Math.ceil(fillLen / filler.length) + 1)).join(filler).slice(0, fillLen) + str
      )
    : str;
}

function padEnd(str, maxLength, opt_fillString) {
  str += '';

  var filler, fillLen, stringLength = str.length;

  return maxLength > stringLength
    ? (
        filler = (opt_fillString !== undefined ? opt_fillString + '' : '') || ' ',
        fillLen = maxLength - stringLength,
        str + (new Array(Math.ceil(fillLen / filler.length) + 1)).join(filler).slice(0, fillLen)
      )
    : str;
}

It has been proposed that in ES7 two new String prototype functions be defined:

This snippet makes this functionality available today using these functions:

padStart(...) API Documentation

Description

Prepends a string with a filler string so that the length of the string is always at least a certain length.

Parameters

  1. str {string}:
    The string to prepend a filler string to.
  2. maxLength {number}:
    The maximum length allowed for the returned string. If this is less than str.length, this will be set to str.length.
  3. opt_fillString {string=}:
    Optional. Defaults to " ". The string to repeatedly prepend to str until the length reaches maxLength.

Returns

Returns str with the filler string prepended to it as many times as necessary until maxLength is reached.

padEnd(...) API Documentation

Description

Appends a string with a filler string so that the length of the string is always at least a certain length.

Parameters

  1. str {string}:
    The string to append a filler string to.
  2. maxLength {number}:
    The maximum length allowed for the returned string. If this is less than str.length, this will be set to str.length.
  3. opt_fillString {string=}:
    Optional. Defaults to " ". The string to repeatedly append to str until the length reaches maxLength.

Returns

Returns str with the filler string appended to it as many times as necessary until maxLength is reached.