Sitemap
DailyJS

JavaScript news and opinion.

String Pad in JavaScript

4 min readAug 12, 2020

--

Press enter or click to view image in full size
Code Tidbit by SamanthaMing.com

It’s super easy to pad a string! Just pass in your desired string and length. The string will be padded until the length has been met. Use padStart to apply it at the start and padEnd to apply it at the end 🎀

const string = 'hi';string.padStart(3, 'c'); // "chi"string.padEnd(4, 'l'); // "hill"

Syntax

This is the syntax of how to use the method.

string.padStart(<maxLength>, <padString>)string.padEnd(<maxLength>, <padString>)

Understanding the Parameters

padEnd and padStart accepts the same parameters.

1. maxLength

This is the max length of the result string.

const result = string.padStart(5);result.length; // 5

When I was learning this, this took me awhile to grasp. I kept thinking it was the amount of times the pad string argument would be repeated. So just want to stress that this parameter is setting the MAX or targeted length of the result string. It is NOT the amount the pad string is repeated. But you’re way smarter than I am, so I’m sure you did not have this confusion 😆

2. padString

--

--

Samantha Ming
Samantha Ming

Written by Samantha Ming

Frontend Developer sharing weekly JS, HTML, CSS code tidbits🔥 Discover them all on samanthaming.com 💛

Responses (2)