Repeat a string three times using JavaScript?

rusty1_rusty1 asked this question 5 months ago
rusty1_rusty1 on Feb 18 · Edited

Using JavaScript, how can I create function or method that takes a string and repeats it a variable number of times.

For instance, it should take this string:


And convert it to this:


Thanks in advance!

3 suggested answers
nick on Mar 14

You can use the ES6 repeat() method:


That will take your string and repeat it i times. In this case, 3 times.

This is an ES6 feature, so make sure you check browser compatibility before using it in a website.

0 replies
moon_man41 on Mar 14

Here's a function you can use:

function repeatString(string, times) {
    let repeatedString = "";

    while (times > 0) {
        repeatedString += string;
        times --;

    return repeatedString;

To repeat your string 3 times, use the function like this:

repeatString("abcd", 3); // "abcdabcdabcd"
0 replies
coderguy on Mar 14 · Edited

Using a for loop:

const num = 3;
const str = "abcd";

let newString = "";

for (let i = 0; i < num; i++) {
  newString += str;

// newString = "abcdabcdabcd"
0 replies