Explaining padStart & padEnd - two ES8 string methods

author-avatar
Paul Shan Mon Feb 20 2017

EcmaScript 2017 or ES8 has introduced two new String prototype methods. padStart and padEnd. Both of them will be used in display related purpose. Even the name says it’s all about “padding”.
You can add some extra spaces or dashes (or any other character), before of after a string.
The specs are still not finalized, so there could be some changes in the signature or contract; however chances are less.

padStart

str.padStart(targetLength, padString);

var str = "paul";
str.padStart(8); //"    paul"
str.padStart(8, 'ab'); //"ababpaul"
str.padStart(8, '-'); //"----paul"
str.padStart(9, 'ab'); //"ababapaul"
str.padStart(5, 'abcd'); //"apaul"
str.padStart(6, ' '); //"  paul"
str.padStart(1, 'a'); //"paul"

padEnd

str.padEnd(maxLength, padString);

var str = "paul";
str.padEnd(8); //"paul    "
str.padEnd(8, 'ab'); //"paulabab"
str.padEnd(8, '-'); //"paul----"
str.padEnd(9, 'ab'); //"paulababa"
str.padEnd(5, 'abcd'); //"paula"
str.padEnd(6, ' '); //"paul  "
str.padEnd(1, 'a'); //"paul"

How does it work

  • You can specify the final length or maxLength of the string.
  • To achieve that maxLength it adds the padString repeatedly to the start or the end of the given string.
  • The default pasString is a space character.
  • If maxLength is lesser than the string length, it does nothing. It will not shorten the string, but will return the unmodified one.
vanilla jsES8

Written By

Paul Shan

Collections

  • E

    ES6

  • R

    React JS

  • C

    CSS

    Cascading style sheets only

  • S

    SEO

    Search engine optimization

  • E

    ES7

  • C

    CMS

    wordpress, drupal, jumla, magento and more


Show All

Tags

vue-js
advanced js
youtube
Web development
vue css
social share buttons
real-life-example
react datetime picker
progra
Online
MathJax
jsfiddle
jquery chart library
instant search using vue
handlebars
event loop
Design
console.log
best practices
imorph

Show All