javascript
  1. javascript-padend

JavaScript padEnd Method

Introduction

This tutorial covers the usage of the padEnd method in JavaScript. The padEnd method is used to pad a string with a specified character or a sequence of characters until the resulting string reaches a desired length.

Syntax

The syntax for the padEnd method is as follows:

string.padEnd(targetLength [, padString]);
  • targetLength: The length of the resulting string.
  • padString (optional): The string to pad the current string with. If not provided, the string is padded with spaces.

Example

Consider a scenario where you want to pad a string to a specific length:

const originalString = 'Hello';
const paddedString = originalString.padEnd(10, '-');

console.log(paddedString); // Output: 'Hello-----'

Output

The output of the example is a string padded with hyphens to reach the target length:

'Hello-----'

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>JavaScript Output</title>
</head>
<body>

<!-- Your JavaScript code goes here -->
<script>
  const originalString = 'Hello';

  // Using padEnd method to pad the string with hyphens
  const paddedString = originalString.padEnd(10, '-');

  // Displaying the result in the HTML document
  document.write('<p>' + paddedString + '</p>');
</script>

</body>
</html>

Try Playground

Explanation

  • The padEnd method appends characters to the end of a string until it reaches the specified length.
  • In the example, the original string 'Hello' is padded with hyphens ('-') to achieve a total length of 10 characters.

Use

  • Formatting Output: Use padEnd to format and align strings in console output or UI elements.
  • Fixed-Length Fields: Ensure consistency in data representation by padding strings to a fixed length in data processing applications.
  • Visual Alignment: Achieve visual alignment in tables or columns by padding strings to a common length.

Important Points

  1. Target Length Limit: The padEnd method does not truncate the string if it exceeds the target length.
  2. Default Padding Character: If no padString is provided, spaces are used as the default padding character.
  3. Immutable Operation: padEnd does not modify the original string; it returns a new padded string.

Summary

The padEnd method in JavaScript provides a convenient way to pad strings to a specified length, ensuring consistent formatting and alignment. Whether for visual presentation or data processing, padEnd is a valuable tool for managing string lengths in JavaScript applications.

Published on: