How to Repeat a String in JavaScript

#javascript #string #es6

Last updated on Sep 5, 2020 by Suraj Sharma



ES6 already has a built-in method String.repeat() to repeat a string for N number of times. It is not supported in older browsers.

In this article, you are going to learn four ways to repeat a string in JavaScript.

So, let’s get started.



Repeat a string for N number of times


1. Using a built-in method


String.repeat() method was introduced in ES6 and all the modern browsers support it,

repeat(count) accepts an argument 'count', which should be greater than or equal to zero and less than +Infinity.


console.log('Hello '.repeat(4)); // 'Hello Hello Hello Hello '
console.log('Hello '.repeat(-1)); // error: Uncaught RangeError: Invalid count value
console.log('Hello '.repeat(0)); // ''


2. Using a Recursive function


We are going to create a recursive function to repeat a string N number of times.


function repeatString(string, times) {
  if (times < 0)
    throw new RangeError('Number must be greater equal than zero');
  if (times === 0) 
    return '';
  if (times === 1)
    return string;
  return string+repeatString(string, times-1);
}

console.log(repeatString('Hello ', 2)) // 'Hello Hello '
console.log(repeatString('Hello ', 0)) // ''
console.log(repeatString('Hello ', -1)) // error: Uncaught RangeError: Number must be greater than or equal to zero


3. Using a Array.join() method


This approach is about creating an empty array of length N+1 and then joining the array elements with the string to be repeated.


function repeatString(string, times) {
  return new Array(times+1).join(string);
}

console.log(repeatString('Hello ', 4)); // 'Hello Hello Hello Hello '

4. Using a For Loop


This solution requires you to loop for N times and concat the string on each iteration.


function repeatString(string, times) {
  let str = times ? string : '';
  for (let i=1; i<times;i++) {
    str += string
  }
  return str;
}

console.log(repeatString('Hello ', 0)) // ''
console.log(repeatString('Hello ', 3)) // 'Hello Hello Hello '


Related Articles



Suraj Sharma is a JavaScript Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.