The left-pad function is a useful utility in programming that allows you to pad a given string from the left side with a specific character. This functionality comes in handy in numerous scenarios, especially when dealing with fixed-width outputs. In this guide, we will explore several APIs of the left-pad
library with code snippets, and also demonstrate an application example.
API Examples for Left-Pad
Basic Left Padding
This is the simplest form of left-padding a string:
const leftPad = require('left-pad'); const result = leftPad('123', 5, '0'); console.log(result); // Outputs: 00123
Left Padding with Different Characters
You can pad the string with different characters:
const result = leftPad('123', 5, '*'); console.log(result); // Outputs: **123
Left Padding with Spaces
Using spaces for padding:
const result = leftPad('123', 5, ' '); console.log(result); // Outputs: " 123"
Left Padding Non-String Values
Left-pad can be used with numbers as well, which are converted to strings:
const result = leftPad(9, 3, '0'); console.log(result); // Outputs: 009
Handling Edge Cases
Various edge cases such as input being already the desired length:
const result = leftPad('12345', 5, '0'); console.log(result); // Outputs: 12345 (no padding needed)
App Example Using Left-Pad
Let’s put it all together in a small application that formats account numbers:
const leftPad = require('left-pad');
function formatAccountNumber(accountNumber) {
return leftPad(accountNumber, 10, '0');
}
const accounts = [
{ name: 'Alice', number: 123 },
{ name: 'Bob', number: 4567 },
{ name: 'Charlie', number: 89 },
];
accounts.forEach(account => {
console.log(`${account.name}: ${formatAccountNumber(account.number)}`);
}); // Outputs: // Alice: 0000000123 // Bob: 0000004567 // Charlie: 0000000089
Through these examples, we have demonstrated how the left-pad
function can be leveraged for a variety of padding tasks. This small utility is a powerful ally when consistent string formatting is required.
Hash: 0cc8ed26e04976bca87d2617e4c0c481592eb2b11129405cad059ba263fe3250