Home >Web Front-end >JS Tutorial >How to Efficiently Repeat a String in JavaScript?

How to Efficiently Repeat a String in JavaScript?

DDD
DDDOriginal
2024-11-24 18:55:12994browse

How to Efficiently Repeat a String in JavaScript?

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!

Statement:
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