Syntax, Parameter and Return Value
Syntax:
_.repeat([string=''], [n=1])
Parameters:
-
[string=''] (string): The string to repeat.
- [n=1] (number): The number of times to repeat the string.
Return Value:
(string) - Returns the repeated string.
Examples
Repeating a String Multiple Times:
JavaScript
var _ = require('lodash');
var text = 'abc';
console.log(_.repeat(text, 3));
You can also try this code with Online Javascript Compiler
Run Code
Output:
'abcabcabc'
Demonstrates repeating a string three times.
Creating a Divider Line:
JavaScript
var divider = _.repeat('-', 20);
console.log(divider);
You can also try this code with Online Javascript Compiler
Run Code
Output:
'--------------------'
Shows how to create a simple divider line for text formatting.
Formatting Text Output:
JavaScript
var spaces = _.repeat(' ', 10);
var message = 'Start' + spaces + 'End';
console.log(message);
You can also try this code with Online Javascript Compiler
Run Code
Output:
'Start End'
An example of using repeated spaces for text alignment.
Generating Test Data:
JavaScript
var testData = _.repeat('Sample Data | ', 5);
console.log(testData);
You can also try this code with Online Javascript Compiler
Run Code
Output:
'Sample Data | Sample Data | Sample Data | Sample Data | Sample Data | '
Demonstrates generating repeated patterns for test data.
Frequently Asked Questions
What happens if the repeat count is set to 0 or a negative number?
If the repeat count n is set to 0 or a negative number, _.repeat() returns an empty string.
Can _.repeat() be used with non-string values?
_.repeat() is designed for strings. Non-string values should be converted to strings before being passed to _.repeat().
Is there a limit to the number of repetitions?
The number of repetitions is limited by memory and performance constraints. Excessively large repeat counts can lead to performance issues or memory overflow.
Conclusion
Lodash's _.repeat() method is a useful tool for generating a new string that repeats a given string a specified number of times. It's handy for creating patterns, formatting output, and generating test data in an efficient and readable manner.
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.