by Sai gowtham

Repeating a string n number of times in JavaScript

Learn, how to repeat a string in JavaScript.

To repeat a string in a specified number of times, we can use the built-in repeat() method in JavaScript.

Here is an example that repeats the following string for 4 times:

const name = "king";

const repeat = name.repeat(4);

console.log(repeat);

Output:

"kingkingkingking"

Similarly, we can also create our repeat() function like this:

function repeat(str, n) {
  if (!str || !n) {
    return;
  }

  let final = "";
  while (n) {
    final += s;
    n--;
  }
  return final;
}

console.log(repeat("sai", 3)); // "saisaisai"

In the above function, we have used the while loop to concatenate the string for n number of times.

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
130,921 students enrolled
48.5 hours of video content
View Course