[Solved] Repeat a String N Times in JavaScript

  

3
Topic starter

Write a JavaScript function that repeats a given string, N times.

The input comes as 2 arguments:

  • The first argument is a string that will represent the one you need to repeat.
  • The second one is a number will represent the times you need to repeat it.

Examples:

Input:
repeat
5

Output:
repeatrepeatrepeatrepeatrepeat


Input:
magic is real
3

Output:
magic is realmagic is realmagic is real


The output is a big string, containing the given one, repeated N times.

1 Answer
2

My JS code:

function repeatStr(input, times) {
    let result = input.repeat(times);
    console.log(result);
}
 
repeatStr("repeat", 5);

and another solution: 

function repS(data, howmany) {
    let endResult = "";
 
    for (let i = 1; i <= howmany; i++) {
        endResult += data;
    }
    console.log(endResult);
 
}
 
repS("magic is real", 3);
Share: