Skip to main content

Command Palette

Search for a command to run...

Padding Strings

Mastering String Manipulation in JavaScript: A Guide to padStart and padEnd

Updated
2 min read
Padding Strings
A

I have been a full-stack developer for twelve years and am currently part of the Cloud FinOps team at Atlassian. I previously ran an App development agency, managing various teams across design and development, leading web, backend and native mobile app developers in Australia and Europe. My strengths are system architecture design and communicating complicated tech to everyday people. Having helped scale tech at numerous startups, I am passionate about making a positive difference. When not working, you can find me writing tech articles and teaching Javascript and React at SheCodes, an initiative helping to get more women into tech. I regularly give talks on various topics, focusing on the impact the technology we build can have. I am devastated by the state of the world, love a good political rant and can often be swearing at no one in particular. I enjoy building things in JavaScript, Deno and Node.

We have been messing with arrays in the last few blogs, so let's switch gears and look at some string methods. There are a lot of built-in methods on a string, but two you might not know are padStart() and padEnd(). So what do they do? They pad a string with another string at the start or the end. Let's take a look at some examples.

Take a phone number. Sometimes, we don't want to show the whole number and one way to obscure the printout is padStart():

const phone = "+61422167343"
const endDigits = phone.slice(-3)

const masked = endDigits.padStart(phone.length, "*")
console.log(masked)

There are more elegant ways of doing this, but it's an excellent example of using one of the pad methods. The first argument is the target length of the string once the string has been padded. The second argument is the string to pad the current string with. If no value is passed, it uses an empty string.

Let's use another example. Say I wanted to print a text table in my console listing something like most rock albums ever sold. I could use padEnd to ensure each cell is the same width.

const ID_WIDTH = 5;
const ARTIST_WIDTH = 20;
const ALBUM_WIDTH = 35;
const SALES_WIDTH = 15;

const albums = [
  { id: 1, artist: "The Wiggles", album: "Wiggle Time", sales: "99M" },
  { id: 2, artist: "The Eagles", album: "Their Greatest Hits (1971–1975)", sales: "45M" },
  { id: 3, artist: "Led Zeppelin", album: "Led Zeppelin IV", sales: "37M" },
  { id: 4, artist: "Pink Floyd", album: "The Wall", sales: "33M" },
];

function displayTable(data) {
  // Headers
  console.log(
    "ID".padEnd(ID_WIDTH) + 
    "Artist".padEnd(ARTIST_WIDTH) + 
    "Album".padEnd(ALBUM_WIDTH) + 
    "Sales".padEnd(SALES_WIDTH)
  );

  // Separator
  console.log("-".repeat(ID_WIDTH + ARTIST_WIDTH + ALBUM_WIDTH + SALES_WIDTH));

  // Data rows
  for (const item of data) {
    const id = item.id.toString().padEnd(ID_WIDTH);
    const artist = item.artist.padEnd(ARTIST_WIDTH);
    const album = item.album.padEnd(ALBUM_WIDTH);
    const sales = item.sales.padEnd(SALES_WIDTH);

    console.log(`${id}${artist}${album}${sales}`);
  }
}

displayTable(albums);

Which would log a table with the following output:

ID   Artist              Album                             Sales         
---------------------------------------------------------------------------
1    The Wiggles         Wiggle Time                       99M           
2    The Eagles          Their Greatest Hits (1971–1975)   45M           
3    Led Zeppelin        Led Zeppelin IV                   37M           
4    Pink Floyd          The Wall                          33M

The pad functions have full browser support (except IE), but you can find the full breakdown here.

JavaScript

Part 3 of 9

JavaScript is an incredible language, and it is constantly evolving. This series will cover some of its newer features you may have missed or never knew about.

Up next

What's In My Array

Mastering Array Search with some, indexOf, and includes in JavaScript