ECMAScript 2017 padEnd() and padStart()

Posted on

Two new methods implemented in the 2017 version of Javascript are padEnd and padStart. Both methods pad a string with second string, until the result is of the desired indicated length. Given that the return value of padEnd and padStart are new Strings, and the original strings are unmodified, the methods a “pure”, as they do not cause side-effects.  As you can see from the examples below, this is true as str1 in the example is unmodified.

Screen Shot 2018-09-08 at 1.04.49 AM

Now the length of our example string, str1 is 17.  If the target length is less than the size of the primary string, the primary string will be returned. If the target length is less than the size of the primary string and the added string, the added string will be truncated to fit the target length. Example below:

Screen Shot 2018-09-08 at 1.14.54 AM.png

If your browser doesn’t have these methods because it doesn’t support ECMAScript 2017 you can actually write your own methods and add them to the String prototype, extending it. I changed the styling such that it can fit in a smaller picture, so heres an example of padEnd() implemented by me: below. See also the repl link if you would like to play with it

Screen Shot 2018-09-08 at 1.37.56 AM

Screen Shot 2018-09-08 at 1.42.44 AM.png

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s