Syntax, Parameter and Return Value
Syntax
_.pad([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 padded string.
Examples
Basic Padding of a String
JavaScript
var _ = require('lodash');
var text = 'hello';
console.log(_.pad(text, 10));

You can also try this code with Online Javascript Compiler
Run Code
Output:
' hello '
Demonstrates padding a string to a total length of 10 characters.
Padding with Custom Characters
JavaScript
var title = 'title';
console.log(_.pad(title, 10, '-='));

You can also try this code with Online Javascript Compiler
Run Code
Output:
'-=title=-='
Shows how to pad a string with a custom character sequence.
Aligning Text for Display
JavaScript
var names = ['Alice', 'Bob', 'Carol'];
var paddedNames = names.map(name => _.pad(name, 10));
console.log(paddedNames.join('\n'));

You can also try this code with Online Javascript Compiler
Run Code
Output:
' Alice '
' Bob '
' Carol '
An example of using _.pad() to align a list of names in a column.
Formatting for Fixed-Width Output
JavaScript
var data = ['123', '45', '6789'];
var formattedData = data.map(d => _.pad(d, 6, '0'));
console.log(formattedData.join('\n'));

You can also try this code with Online Javascript Compiler
Run Code
Output:
'001230'
'000450'
'067890'
Demonstrates using padding to format numbers for a fixed-width output.
Frequently Asked Questions
How does _.pad() handle strings longer than the specified length?
If the string is already longer than the specified length, _.pad() returns the original string without any modifications.
Can _.pad() pad strings with different characters on each side?
_.pad() uses the same characters for both sides. For different characters on each side, you would need to use _.padStart() and _.padEnd() separately.
Is the padding applied evenly on both sides?
_.pad() attempts to pad evenly on both sides. If the padding can't be divided evenly, the extra character is added to the end of the string.
Conclusion
Lodash's _.pad() method is an effective tool for extending the length of a string by adding padding characters symmetrically to both sides. It's useful for text formatting, aligning output, and preparing strings for specific display or file format requirements.
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.