ES8 String padding

ES8 introduced the following new string methods.

  • padStart
  • padEnd

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

The characters add to the 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

exampleoutputdescription
'sentences'.padStart(9)'sentencesif length of input is less than output, still prints original
'sentences'.padStart(10)'sentencesif length of input is greater than output, space padding added to start
'sentences'.padStart(12)'sentencesspace padding added to start
'sentences'.padStart(12,'my)'mymsentencespadString added to start
'sentences'.padStart(10,'my')'msentencespadString added to start
'sentences'.padStart(15,'my')'mymymysentencespadString 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:

exampleoutputdescription
'hellojohn'.padEnd(9)'hellojohnif length of input is less than output, still prints original
'hellojohn'.padEnd(10)'hellojohnif length of input is greater than output, space padding added to end
'hellojohn'.padEnd(12)'hellojohnspace padding added to end
'hellojohn'.padEnd(12,'my)'hellojohnmympadString added to end
'hellojohn'.padEnd(10,'my')'hellojohnmpadString added to end
'hellojohn'.padEnd(15,'my')'hellojohnmymymypadString added to end