How to pad the end of a string with another string until the desired length is achieved : padEnd()

Java Script @ Freshers.in

The padEnd() method in JavaScript is used to pad the end of a string with another string until the desired length is achieved. This method is particularly useful in formatting scenarios where the visual presentation of data is important. Unlike some other string methods, padEnd() does not change the original string but instead returns a new string.

Syntax: The padEnd() method is invoked with the following syntax:

string.padEnd(targetLength [, padString])

targetLength: This parameter is the integer indicating the length of the new string after the padding operation. If the value is less than the original string’s length, the string is returned unchanged.

padString (optional): This is the string to append to the original string. If omitted, the space character (” “) is used as the default padding. If padString is too long to stay within targetLength, it will be truncated.

Examples and execution:

These examples can be executed in any JavaScript runtime environment, such as browser developer consoles, online IDEs, or a Node.js setup.

Basic usage:

let baseString = "50";
let paddedString = baseString.padEnd(5, "*");
console.log(paddedString); // Outputs: "50***"
Aligning text output:
function alignText(text, length) {
    let alignedText = text.padEnd(length, " ");
    console.log(alignedText);
}
let text = "JavaScript";
alignText(text, 20); // Outputs: "JavaScript          "
Creating a visual element:
let header = "Chapter 1:";
let formattedHeader = header.padEnd(20, "-");
console.log(formattedHeader); // Outputs: "Chapter 1:-----------"
Formatting a report:
function formatReport(title, pageLength) {
    let formattedTitle = title.padEnd(pageLength, ".");
    console.log(formattedTitle);
}
let reportTitle = "Annual Summary";
formatReport(reportTitle, 30); // Outputs: "Annual Summary.............."
Author: user