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

How to Efficiently Duplicate a String Multiple Times in JavaScript?

Mary-Kate Olsen
Release: 2024-11-18 10:27:02
Original
983 people have browsed it

How to Efficiently Duplicate a String Multiple Times in JavaScript?

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

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!

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