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

How to Efficiently Repeat a String in JavaScript?

DDD
Release: 2024-11-24 18:55:12
Original
985 people have browsed it

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

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template