Syntax, Parameter and Return Value
Syntax:
_.padEnd([string=''], [length=0], [chars=' '])
Parameters:
-
[string=''] (string): The string to pad.
-
[length=0] (number): The padding length.
- [chars=' '] (string): The string used as padding.
Return Value:
(string) - Returns the right-padded string.
Examples
Padding the End of a String:
JavaScript
var _ = require('lodash');
var text = 'hello';
console.log(_.padEnd(text, 10));
You can also try this code with Online Javascript Compiler
Run Code
Output:
'hello '
Demonstrates extending a string to a total length of 10 characters by adding spaces to the end.
Padding with Custom Characters:
JavaScript
var message = 'Note:';
console.log(_.padEnd(message, 10, '*'));
You can also try this code with Online Javascript Compiler
Run Code
Output:
'Note:*****'
Shows padding the end of a string with a custom character.
Aligning Text in Table Columns:
JavaScript
var items = ['Apple', 'Banana', 'Cherry'];
var paddedItems = items.map(item => _.padEnd(item, 10));
console.log(paddedItems.join('\n'));
You can also try this code with Online Javascript Compiler
Run Code
Output:
'Apple '
'Banana '
'Cherry '
An example of using _.padEnd() to align text in a column format.
Formatting Data for Fixed-Width Output:
JavaScript
var ids = ['123', '4567', '89'];
var formattedIds = ids.map(id => _.padEnd(id, 5, '0'));
console.log(formattedIds.join('\n'));
You can also try this code with Online Javascript Compiler
Run Code
Output:
'12300'
'45670'
'89000'
Demonstrates using padding to format data for a fixed-width output.
Frequently Asked Questions
How does _.padEnd() handle strings longer than the specified length?
If the string is already longer than the specified length, _.padEnd() returns the original string without adding any padding.
Can _.padEnd() pad with multiple characters?
Yes, you can specify a string of multiple characters for padding, and _.padEnd() will repeat this string until the total length is reached.
Is the padding applied evenly when using multiple characters?
If the padding string needs to be truncated to achieve the specified length, _.padEnd() will truncate the padding string at the end to fit the required length.
Conclusion
Lodash's _.padEnd() method is a valuable tool for extending the length of a string by adding padding characters to its end. It's useful for aligning text, preparing data for fixed-width formats, and ensuring uniform string lengths in various text formatting and data processing tasks.
You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSA, DBMS, Competitive Programming, Python, Java, JavaScript, etc.
Also, check out some of the Guided Paths on topics such as Data Structure and Algorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, System Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.