How to Repeat a String Using JavaScript

Mehvish Ashiq Feb 02, 2024
  1. Different Ways to Repeat a String Using JavaScript
  2. Use the while Loop to Repeat a String Using JavaScript
  3. Use Recursion to Repeat a String in JavaScript
  4. Use ES6 repeat() Function to Repeat a String Using JavaScript
  5. Use the join() Method to Repeat a String Using JavaScript
  6. Use Lodash’s repeat() Method to Repeat a String Using JavaScript
How to Repeat a String Using JavaScript

This tutorial shows how to repeat a string using JavaScript. Here, repeating a string means duplicating the exact string a particular number of times.

Different Ways to Repeat a String Using JavaScript

We can use different approaches to repeat a string a specified number of times. We can use any one of the following according to the project needs.

  • while loop
  • Recursion
  • ES6 native repeat() function
  • Array’s join() method
  • The repeat() function of Lodash

Use the while Loop to Repeat a String Using JavaScript

function repeatStr(str, numOfTimes) {
  var repeatedStr = '';

  while (numOfTimes > 0) {
    repeatedStr += str;
    numOfTimes--;
  }

  return repeatedStr;
}

console.log(repeatStr('Hi', 6));

Output:

"HiHiHiHiHiHi"

We pass the string Hi and the number 6 to the repeatStr() method that uses the while loop to iterate the provided string for the specified number of times. Here, it is printing Hi six times.

We can also do the same for one character by providing one character as the first argument and a number as the second argument. For instance, repeatStr('M', 5).

Use Recursion to Repeat a String in JavaScript

Recursion is where a function calls itself to repeat an operation until it gets the desired results.

In recursion, the order of writing code is important to meet the goal. Otherwise, the function will keep calling itself as it cannot find an endpoint (stop condition).

To let the function work property, we define the base case that tells the stop condition. Further, we write the recursive case to call the function itself.

Check the following example.

function repeatStr(str, numOfTimes) {
  if (numOfTimes < 0) return '';
  if (numOfTimes === 1)
    return str;
  else
    return str + repeatStr(str, numOfTimes - 1);
}

console.log(repeatStr('Hi', 6));

Output:

"HiHiHiHiHiHi"

Here, the function repeatStr() checks the numOfTimes, if it is less than zero then returns empty string.

If the numOfTimes is 1, it returns the string as it is passed. Otherwise, perform the recursive calls to iterate over an operation to get the expected output.

Use ES6 repeat() Function to Repeat a String Using JavaScript

function repeatStr(str, numOfTimes) {
  if (numOfTimes > 0)
    return str.repeat(numOfTimes);
  else
    return '';
}

console.log(repeatStr('xyz', 2));

Output:

"xyzxyz"

Here, we use the ES6 native repeat() method that accepts a number as an argument and repeats the string for that number of times.

For instance, the repeat() method is iterating two times in the upper code snippet. The repeat() method does not modify the original string but constructs and returns the repeated string.

If we pass a float number, it would be converted to an integer (see the following code). If we don’t provide the number or pass zero (0), it returns an empty string.

It throws RangeError if the specified number is negative or not less than infinity. Let’s understand it by writing a small chunk of code.

var str = 'xyz';

console.log(str.repeat(2));      // xyzxyz
console.log(str.repeat(0));      // ""
console.log(str.repeat());       // ""
console.log(str.repeat(3.4));    // xyzxyzxyz
console.log(str.repeat(-1));     // RangeError
console.log(str.repeat(1 / 0));  // RangeError

Use the join() Method to Repeat a String Using JavaScript

function repeatStr() {
  var str = 'Hello';
  var repeatedStr = '';
  repeatedStr = Array(3).join(str);
  return repeatedStr;
}

console.log(repeatStr());

Output:

"HelloHello"

We use Array’s join() function to join the string a particular number of times.

If we wrote 3, you might wonder why we are getting Hello twice. It is because the array starts from 0 and ends at n-1.

This is why the join() method joins the provided string for n-1 number of times.

Use Lodash’s repeat() Method to Repeat a String Using JavaScript

const _ = require('lodash');

function repeatStr(str, numOfTimes) {
  if (numOfTimes > 0)
    return _.repeat(str, numOfTimes);
  else
    return '';
}

console.log(repeatStr('xyz', 2));

Output:

"xyzxyz"

Here, the repeat() method of the Lodash library also repeats the string as the ES6 repeat() method does.

The only difference is that Lodash’s repeat() method takes the string and count as parameters while ES6’s repeat() method takes only one parameter: count.

You can find more about _.repeat() here.

Mehvish Ashiq avatar Mehvish Ashiq avatar

Mehvish Ashiq is a former Java Programmer and a Data Science enthusiast who leverages her expertise to help others to learn and grow by creating interesting, useful, and reader-friendly content in Computer Programming, Data Science, and Technology.

LinkedIn GitHub Facebook

Related Article - JavaScript String