Summary: in this tutorial, you will learn how to use the JavaScript String padEnd()
method to pad a string from the end to a certain length.
Introduction to the JavaScript padEnd() method
The padEnd()
method pads the end of a string with another string until the resulting string reaches a specified length.
Here’s the syntax of the padEnd()
method:
string.padEnd(targetLength, padString)
Code language: CSS (css)
In this syntax:
targetLength
is the desired length of the resulting string after the input string is padded. If thetargetLength
is less than or equal to the length of the input string, thepadEnd()
method returns the input string as-is.- The
padString
is an optional parameter, specifying the string to pad the current string with. ThepadString
defaults to a space character (' '
). This means that thepadEnd()
method will use a space character to pad the input string if you skip thepadString
argument. If thepadString
is too long to stay within thetargetLength
, thepadEnd()
method will truncate it.
In practice, you’ll find the padEnd()
useful in various scenarios, such as formatting text, aligning data, and more.
Note that to pad from the beginning of a string, you use the padStart() method.
JavaScript padEnd() method examples
Let’s take some examples of using the padEnd()
method.
1) Basic JavaScript padEnd() method example
The following example uses the padEnd()
method to pad a string from the end of a specified string:
let s = 'ha'.padEnd(10, 'ha');
console.log({ s });
s = 'yahoo'.padEnd(20, 'o');
console.log({ s });
Code language: JavaScript (javascript)
Output:
{ s: 'hahahahaha' }
{ s: 'yahooooooooooooooooo' }
Code language: CSS (css)
2) Formating table data
When developing CLI applications, you may want to display data in table format. To ensure each column has a consistent width, you can use the padEnd()
method. For example:
const formatTable = (data, cellWidth = 20) => {
data.forEach((row) => {
let formattedRow = row.map((cell) => cell.padEnd(cellWidth)).join('|');
console.log(formattedRow);
});
};
let data = [
['Name', 'Age', 'City'],
['Alice', '30', 'New York'],
['Bob', '25', 'San Francisco'],
['Charlie', '35', 'Los Angeles'],
];
formatTable(data);
Code language: JavaScript (javascript)
Output:
Name |Age |City
Alice |30 |New York
Bob |25 |San Francisco
Charlie |35 |Los Angeles
Code language: Shell Session (shell)
Summary
- Use the
padEnd()
method to pad from the end of a string with another string until the resulting string reaches a certain length.