How to pad a string in JavaScript

ES2017 added the padStart() and padEnd() methods, which add whitespace or other characters to a string until it reaches a specific length.

Dr. Derek Austin 🥳
Coding at Dawn
Published in
5 min readSep 22, 2019

--

Photo by Aaron Burden on Unsplash

What is padding a string?

Padding a string in JavaScript refers to filling a string up with a repeated character or string of characters, usually whitespace.

The string is padded to a certain length, which is what is passed to the String.prototype methods .padStart() and .padEnd().

Calling .padStart(length) or .padEnd(length) returns a new string of the given length, with the start or end of the string padded with spaces.

These padding functions do not modify the string that they are called on.

Both .padStart() and .padEnd() take two parameters, the length in characters to pad the string to and the string to be repeated while padding:

--

--

Dr. Derek Austin 🥳
Coding at Dawn

Hi, I'm Doctor Derek! I've been a professional web developer since 2005, and I love writing about programming with JavaScript, TypeScript, React, Next.js & Git.