Home > Web Front-end > JS Tutorial > body text

How can I efficiently repeat a string multiple times in JavaScript?

Susan Sarandon
Release: 2024-11-18 02:47:02
Original
998 people have browsed it

How can I efficiently repeat a string multiple times in JavaScript?

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"
Copy after login

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;
  };
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template