Home > Web Front-end > JS Tutorial > How Can I Repeat a String Multiple Times in JavaScript?

How Can I Repeat a String Multiple Times in JavaScript?

Linda Hamilton
Release: 2024-11-17 18:29:02
Original
960 people have browsed it

How Can I Repeat a String Multiple Times in JavaScript?

Repeating Strings in JavaScript

In Perl, repetition of strings is achieved using the syntax $a = "a" x 10. Is there an equivalent approach in JavaScript?

Solution:

JavaScript provides a built-in method called repeat(), which allows you to repeat a string a specified number of times. Simply use the syntax:

"a".repeat(10);
Copy after login

This will result in the string "aaaaaaaaaa".

Alternative Approach:

Prior to the introduction of repeat(), a common technique involved creating an array of the desired length and joining each element with the string to be repeated:

Array(11).join("a"); // "aaaaaaaaaa"
Copy after login

Benchmarking:

As pointed out in the answer, benchmarks suggest that using a for loop to append the character may be faster in Safari and Chrome, but not in Firefox. However, the repeat() method remains a simplified and concise approach.

The above is the detailed content of How Can I 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