Repeating string for specific number of times using JavaScript


In the realm of JavaScript programming, the ability to repeat a string for a specific number of times is a significant functionality that can greatly enhance the efficiency and versatility of code. JavaScript, being a flexible and powerful language, provides developers with the tools to accomplish this task effortlessly. Although the concept may seem elementary, mastering the art of repeating a string for a specific number of times requires an understanding of the underlying mechanisms and the appropriate utilization of rarely used functions. In this article, we will explore the intricacies of repeating strings using JavaScript, diving into the less frequented techniques and functions that enable developers to achieve this task with elegance and precision.

Problem Statement

Write a JavaScript function that takes a string and a positive integer as input and returns a new string that repeats the input string for the specified number of times. If the input string is empty or the specified number of times is zero, the function should return an empty string.

Sample Input −

String: "Hello"
Number of Times: 3

Sample Output −

"HelloHelloHello" 

Approach

In this article, we are going to see a number of different ways to solve the above problem statement in JavaScript −

  • Using a for loop

  • Using the repeat() method

  • Using the Array and join() method

  • Using recursion

  • Using the while loop

  • Using the reduce() method

  • Using the concat() method and Array.from()

  • Using the padEnd() method and repeat()

Method 1: Using a for Loop

To repeat a string using a for loop, initialize an empty string variable. Then, iterate the specified number of times using a for loop. During each iteration, concatenate the given string to the result string. Finally, return the resulting string after the loop completes.

Example

The function repeatString takes a string and a number as input. It initializes an empty result string and uses a for loop to concatenate the input string to the result string for the specified number of iterations. Ultimately, it returns the resulting string.

function repeatString(str, times) {
   let result = '';
   for (let i = 0; i < times; i++) {
      result += str;
   }
   return result;
}
console.log(repeatString('abc', 3));

Output

The following is the console output −

abcabcabc

Method 2: Using the Repeat() Method

To repeat a string using the repeat() method, simply call the repeat() method on the desired string and provide the number of times to repeat as the argument. This method will repeat the string the specified number of times and return the repeated string as the result.

Example

The function repeatString takes a str string and times number as parameters. Using the repeat() method on the str string with the times number as the argument, we repeat the string accordingly. Afterward, the repeated string is returned by the function.

function repeatString(str, times) {
   return str.repeat(times);
}
console.log(repeatString('abc', 3));

Output

The following is the console output −

abcabcabc

Method 3: Using the Array and Join() Method

To repeat a string a specified number of times using the Array and join() method, start by creating a new array with the desired length using the Array() constructor. Then, utilize the fill() method to populate each slot of the array with the given string. Next, apply the join() method to concatenate all the elements of the array into a single string, effectively repeating the input string the desired number of times. Finally, return the repeated string as the output.

Example

In the repeatString function, we create a new array of length times using the Array() constructor. We fill each slot of the array with the str string using the fill() method. Then, we use the join() method to combine all the array elements into a single string, effectively repeating the str times number of times.

function repeatString(str, times) {
   return Array(times).fill(str).join('');
}
console.log(repeatString('abc', 3));

Output

The following is the console output −

abcabcabc

Method 4: Using Recursion

With recursion, the repeatString function can be implemented in the following way: first, check if the base case is met by verifying if the times variable is equal to 0; if so, return an empty string. If not, recursively invoke the repeatString function with the str and times - 1 arguments. Concatenate the str string to the result of the recursive call. Finally, return the repeated string as the output.

Example

The repeatString function takes a string (str) and a number (times) as parameters. If times is 0, an empty string is returned as the base case. Otherwise, the function recursively calls itself with the updated arguments of str and times - 1, and concatenates str to the result. This recursion repeats the string a specified number of times. The function ultimately returns the repeated string.

function repeatString(str, times) {
   if (times === 0) {
      return '';
   } else {
      return str + repeatString(str, times - 1);
   }
}
console.log(repeatString('abc', 3));

Output

The following is the console output −

abcabcabc

Method 5: Using the While Loop

To repeat a string using a while loop, start by initializing an empty string variable. Then, use a while loop to iterate until a specified condition is met. Within each iteration, concatenate the original string to the result string and decrement a counter variable. Finally, return the resulting string after the loop has finished executing.

Example

To repeat a string a specified number of times, initialize an empty string variable. Utilize a while loop that continues until the desired number of repetitions is reached. Within each iteration, concatenate the original string to the result string and decrement the repetition count. Finally, return the resulting string that contains the repeated sequence.

function repeatString(str, times) {
   let result = '';
   while (times > 0) {
      result += str;
      times--;
   }
   return result;
}
console.log(repeatString('abc', 3));

Output

The following is the console output −

abcabcabc

Method 6: Using the Reduce() Method

To create an accumulated string using the reduce() method, start by creating an array of a specified length using the Array() constructor. Then, apply the reduce() method on the array, providing a callback function and an initial value of an empty string. In each iteration, concatenate the str string to the accumulator. Finally, return the accumulated string as the result.

Example

To create a string of length times, use the Array() constructor to create an array. Then, apply the reduce() method on the array with a callback function and an initial value of an empty string. Within each iteration, concatenate the str string to the accumulator. Finally, return the accumulated string.

function repeatString(str, times) {
   return Array(times).fill(str).reduce((acc, val) => acc + val, '');
}
console.log(repeatString('abc', 3)); 

Output

The following is the console output −

abcabcabc

Method 7: Using the Concat() Method and Array.from()

To repeat a string a certain number of times using the concat() method and Array.from(), you can start by using Array.from() with an object containing a length property set to the desired number of repetitions. Then, map over the resulting array and return the string you want to repeat in each iteration. After that, utilize the join() method to combine all the elements of the array into a single string, effectively repeating the original string the specified number of times. Finally, return the repeated string as the result.

Example

The function repeatString takes a string str and a number times as inputs. Using the Array.from() method with a length property set to times, an array of length times is created. We iterate over the array, returning the str string in each iteration. Finally, the join() method is used to merge all the elements of the array into a single string, resulting in the repetition of the str string times number of times.

function repeatString(str, times) {
   return Array.from({ length: times }).map(() => str).join('');
}
console.log(repeatString('abc', 3));

Output

The following is the console output −

abcabcabc

Method 8: Using the PadEnd() Method and Repeat()

To repeat a string using the padEnd() method and repeat(), first utilize the repeat() method on the input string, specifying the desired number of repetitions. This will duplicate the string accordingly. Then, apply the padEnd() method on the repeated string, indicating the target length as the original string's length multiplied by the desired number of repetitions, and the original string as the padding. Finally, return the padded string, effectively producing the repeated string with the desired number of repetitions.

Example

The function repeatString takes a string str and a number times as parameters. It uses the repeat() method on str, passing times as the argument to repeat the string. The repeated string is then padded using the padEnd() method with the desired length as str.length * times and the original str as the padding. The function returns the padded string, effectively repeating str times number of times.

function repeatString(str, times) {
   return str.repeat(times).padEnd(str.length * times, str);
}
console.log(repeatString('abc', 3));

Output

The following is the console output −

abcabcabc

Conclusion

In denouement, the ability to replicate a string for a specific number of iterations using JavaScript introduces a myriad of possibilities for developers seeking to customize and manipulate data. This esoteric yet powerful technique empowers programmers to create intricate patterns and intricate textual representations with precision and finesse. By leveraging this functionality, developers can infuse their applications with a sense of uniqueness and dynamism, captivating users with an unparalleled visual experience. In conclusion, harnessing the arcane potential of JavaScript to repeat strings allows for the creation of extraordinary applications that transcend conventional boundaries and leave an indelible impression on users.

Updated on: 04-Aug-2023

854 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements