[ Web Proxy ]
URL:
Viewing: https://www.javascripttutorial.net/javascript-string-methods/string-padend/ [Back]  [Original]

JavaScript String padEnd
Skip to content

String.prototype.padEnd()

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.

JavaScript String padEnd [JavaScript String padEnd]

Here’s the syntax of the padEnd() method:

string.padEnd(targetLength, padString)Code language: CSS (css)

In this syntax:

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 AngelesCode language: Shell Session (shell)

Summary

Was this tutorial helpful ?
Yes No
Search …:

Searching

Trimming

Padding

Extracting

Concatenating

Replacing

Copyright © 2009 - Present by JavaScript Tutorial Website. All Right Reserved.


Web Proxy Viewer  |  New URL  |  Original Page