In this quick tutorial, you’ll learn how to repeat string in JavaScript with an without using built in methods.

Repeat String Using String Concatenation

You can repeat a string n number of times using a for loop and concatenating the string. An example to repeat string :

function repeatString(n, str) {
  let output = ''
  for(let i = 0; i < n; i++) {
    output+=str
  }
  return output
}

console.log(repeatString(3,'hello'))

You can also add the above method as a String prototype method to repeat.

const repeatString = function (n) {
  let output = ''
  for(let i = 0; i < n; i++) {
    output+=this
  }
  return output
}

String.prototype.repeatS = repeatString

console.log('Hello'.repeatS(3))

Repeat String Using Repeat Method

ES6 provides a method called repeat which helps to repeat a string n number of times. Here is how you can use the repeat method in JavaScript.

// ES6 method repeat to repeat string
console.log('Hello'.repeat(5))

Wrapping It Up

In this quick tutorial, you learnt about two ways to repeat string in JavaScript. If you know of any other way to repeat string in JavaScript, do let us know in the comments below.