Repeat String in Javascript
Query: How do I efficacement duplicate a string multiple times?
Answer: The optimal method to repeat a string in Javascript is through the String prototype. Unlike the provided function, which employs an array to concatenate the repeated string, the prototype approach constructs an array with the desired length and concatenates it directly with the provided string.
Here's an optimised implementation:
String.prototype.repeat = function(num) { return new Array(num + 1).join(this); } console.log("string to repeat\n".repeat(4));
This function assigns a repeat method to the String object. It creates an array of the proper length and joins it with the desired string, eliminating the unnecessary creation and manipulation of an intermediate array.
The above is the detailed content of How to Efficiently Duplicate a String Multiple Times in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!