Repeat String in Javascript
Question:
How can we efficiently return a string repeated a specified number of times?
Answer:
Extended Approach:
The provided code defines a function repeat that iteratively constructs an array filled with the input string and then joins them to form the repeated string.
Concise Approach Using Array:
An alternative solution is to leverage the join method directly on the String object:
String.prototype.repeat = function(num) { return new Array(num + 1).join(this); }
This method optimizes performance by avoiding array creation and subsequent joining operations.
Example:
"string to repeat\n".repeat(4); // "string to repeat\nstring to repeat\nstring to repeat\nstring to repeat\n"
The above is the detailed content of How to Efficiently Repeat a String in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!