The padStart() method pads the current string with another string (multiple times, if needed) until the resulting string reaches the given length. The padding is applied from the start (left) of the current string. It’s important to note that padStart() does not mutate the original string but returns a new string. If the value to pad the string exceeds the required length, it’s sliced to fit precisely. The padStart() method in JavaScript is an invaluable function when working with string data, especially in scenarios requiring the alignment of text or the standardization of string presentation.
Syntax:
The syntax for padStart() is shown below:
string.padStart(targetLength [, padString])
targetLength: The length of the resulting string once the current string has been padded. If this parameter is less than the current string’s length, the current string is returned as is.
padString (optional): The string to pad the current string with. If this string is too long to stay within the target length, it’ll be sliced and applied to the start of the current string. The default value is ” ” (U+0020 ‘SPACE’).
Examples and execution:
These examples can be run in any JavaScript environment, such as a browser’s developer tools, an online code playground, or a Node.js environment.
Basic usage:
let originalString = "5";
let paddedString = originalString.padStart(2, "0");
console.log(paddedString); // Outputs: "05"
function formatID(id) {
let formattedID = id.toString().padStart(4, "0");
console.log("Formatted ID:", formattedID);
}
let userID = 12;
formatID(userID); // Outputs: "Formatted ID: 0012"
let baseString = "123";
let complexPaddedString = baseString.padStart(10, "abc");
console.log(complexPaddedString); // Outputs: "abcabca123"
Example – Aligning console output:
function displayAligned(numbers) {
numbers.forEach(number => {
console.log(number.toString().padStart(5, " "));
});
}
let numbersList = [1, 90, 1234];
displayAligned(numbersList); // Outputs:
// " 1"
// " 90"
// " 1234"
Get more articles on Java Script
Read more on Shell and Linux related articles
Refer more on python here : Python