ES8 String padding

ES8 introduced the following new string methods.

  • padStart
  • padEnd

padding methods allow modifying string by padding characters to string and returning the new string.

The characters add to start or end using padStart or padEnd methods.

String padStart method

Syntax

string padStart(destinationLength,\[,padString\])

Parameters and returns

  • destinationLength, length of output string after padding string characters to an input string
  • padString, the characters to be added. Optional, default is space.
  • `returns' output new string with length of destinationLength after padString is added.

Example

String padStart method

Padding extra characters to original string from starting index

example output description
'sentences'.padStart(9)' sentences if length of input is less than output, still prints original
'sentences'.padStart(10)' sentences if length of input is greater than output, space padding added to start
'sentences'.padStart(12)' sentences space padding added to start
'sentences'.padStart(12,'my)' mymsentences padString added to start
'sentences'.padStart(10,'my')' msentences padString added to start
'sentences'.padStart(15,'my')' mymymysentences padString added to start

String padEnd method

Padding string to original input string from end index

Syntax

string padEnd(destinationLength,\[,padString\])

Parameters and returns

  • destinationLength, length of output string after adding string characters to the input string
  • padString, the characters to be added. Optional, default is space.
  • `returns' output new string with length of destinationLength after padString is added.

Example

example output description
'hellojohn'.padEnd(9)' hellojohn if length of input is less than output, still prints original
'hellojohn'.padEnd(10)' hellojohn if length of input is greater than output, space padding added to end
'hellojohn'.padEnd(12)' hellojohn space padding added to end
'hellojohn'.padEnd(12,'my)' hellojohnmym padString added to end
'hellojohn'.padEnd(10,'my')' hellojohnm padString added to end
'hellojohn'.padEnd(15,'my')' hellojohnmymymy padString added to end