Repeat String in Javascript
In Javascript, repeating a string multiple times is a common task. To achieve this, you can use various methods.
One common approach is to use a loop to concatenate the string to itself repeatedly. However, this method is not very efficient for large string repetitions.
A more efficient approach is to use the repeat() method on the String prototype. This method accepts an integer representing the number of times the string should be repeated and returns the repeated string. For example:
const str = "Hello"; const repeatedStr = str.repeat(3); // Output: "HelloHelloHello"
The repeat() method was added to the String prototype in ECMAScript 6 (ES6). If you are using an older version of Javascript, you can use a polyfill to implement the method. Here is an example of a polyfill:
if (!String.prototype.repeat) { String.prototype.repeat = function(count) { if (count < 0) { throw new RangeError("repeat count cannot be negative"); } if (count === Infinity) { throw new RangeError("repeat count cannot be Infinity"); } let result = ""; for (let i = 0; i < count; i++) { result += this; } return result; }; }
The above is the detailed content of How can I efficiently repeat a string multiple times in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!