ES8 - String padding

This tutorial covers String padding latest javascript features introduced in ES8, ES2017..

ES8 String padding

ES8 introduced following new string methods. - padStart - padEnd

padding methods allows to modify string by padding characters to string and returns new string. The characters can be added 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 input string - padString, the characters to be added. Optional, default is empty 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 ading string characters to input string - padString, the characters to be added. Optional, default is empty 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
Prev Next