JavaScript repeat string

In this tutorial, we’re going to figure out ways to repeat the same string ‘n’ number of times, where n is a positive whole number.

ES6 repeat() method

The easiest way of doing this is by using the repeat() method, which is a pre-defined method in JavaScript.

Introduction

In the example below, I’ve created a variable str which holds the string value ‘Hello’.

Then, I’ve used the repeat() method on that string. Notice how I’ve sent just one argument with the function call (5). I’m asking the browser to repeat the string (‘Hello’) 5 times, as shown in the final result below:

let str = 'Hello';
let repeatStr = str.repeat(5);
console.log(repeatStr); //HelloHelloHelloHelloHello 

Non-integer argument values

You’re better off giving integer values as arguments to the repeat() method, but by some chance, if you end up sending a floating-point value, don’t worry. Your browser will just round the number down to the nearest whole number and proceed as normal.

let repeatStr = str.repeat(3.8);
console.log(repeatStr); //HelloHelloHello 

As you can see in the example above, 3.8 was rounded down to 3, even though 0.8 is almost 1, so be careful when sending over floating-point values.

Negative argument values

Even though repeat() works with all kinds of positive numeric values, it just does not work with negative values. You’ll get back a RangeError that says the number you’ve sent is an Invalid count value, as shown below:

let repeatStr = str.repeat(-5);
console.log(repeatStr); //Uncaught RangeError - Invalid count value: -5 

0 as the argument

The repeat() method works similar to a multiplication operation (but only on positive values). So, if you send 0 as the argument, you can image what would happen.

Yes, that’s right. You’ll get an empty string because something multiplied by 0 is always 0, and the string equivalent of 0 is an empty string, as shown below:

let repeatStr = str.repeat(0);
console.log(repeatStr); //Empty string = '' 

String concatenation to repeat a string

So far, we’ve looked at using a pre-defined JavaScript method to repeat a string the number of times we like.

There are manual methods to achieve the same. They take more time and lines of code to write, but it’s always better to learn the manual ways of doing things as well, so you can apply the same methodology in other problems that won’t work with pre-defined methods.

For loop

In this section, let’s use the for loop to repeat a string. To start with, let’s create a function to achieve our result. This function accepts the string, and the number of times you want the repetition to happen, as its arguments.

Inside the function, let’s create a variable called newStr and assign an empty string to it. This variable is going to hold our result.

Now, let’s create a for loop that loops from 0 to n – 1 (a total of n times). For every iteration of the loop, append the value of the string to newStr, and finally return newStr after the loop is done.

We’ve effectively created a new string where we’ve repeated the given string ‘n’ number of times, as seen in the example below:

const repeatStr = (str, n) => {
    let newStr = '';
    for(let i = 0; i < n; i++) {
        newStr += str;
    }
    return newStr;
}

console.log(repeatStr('Hello',5)); //HelloHelloHelloHelloHello 

While loop

We can repeat the same procedure we used with the for loop in the last section for a while loop, as seen below:

const repeatStr = (str, n) => {
    let newStr = '';
    let i = 0;
    while(i < n) {
        newStr += str;
        i++;
    }
    return newStr;
} 

Using a JavaScript recursive function to repeat a string

Now comes the interesting part. If you’d like to save some lines of code, you can go ahead and create a recursion in your function.

You need to look out for infinite recursion though. So, make sure you create checkpoints for when n is 0 (return an empty string) or when n reaches down to 1 (return the final repeated string).

Otherwise, return str + repeatStr(str, n – 1), which would add the value of str one more time to the original string (str) and call the repeatStr method again after decreasing the value of n by 1.

const repeatStr = (str, n) => {
    if(n === 0) return '';
    if(n === 1) return str;
    return str + repeatStr(str,n-1);
} 

Array methods to repeat a string in JavaScript

There are a lot of array methods that’ll be just perfect for our purpose. The only issue is that these methods work only with arrays, and not strings.

But don’t worry. We have our join() method to help us out.

All we need to do is repeat the string into multiple elements of an array, the number of elements in the array equaling the value of ‘n’, and then join the elements into a string by using the join() method.

The join() method can be used to join the elements of an array into a string, based on the join condition we specify when calling the method.

For instance, if we specify the join condition as an empty string, which is what we’ll be doing in this case, then the browser will join every element (which contains a copy of the string), with no space, one after the other, hence forming a complete string of repeated substrings.

If you’d like a space between every repetition, you can always specify a single space as the join condition.

See, this is an advantage of using array methods. You can now specify how the repetition happens, and if you need connecting characters like commas or spaces in between or not.

With repeat(), you didn’t have that option, though you could have done the same while working with the manual methods (for, while and recursion).

Use push and join together

We can create a very simple algorithm using the array push and join methods. It goes like this:

1. Create an empty array arr
2. Create a for loop that iterates from 0 to n – 1, where n is the number of times you want to repeat the given string
3. For every iteration, push a copy of str, which is the given string, into arr using the push method.
4. Now, the array contains n number of elements, each with a copy of str. Once the for loop is done, join all the elements using an empty string (or the connecting character you like), and return the newly formed string. Simple!

const repeatStr = (str, n) => {
    let arr = [];
    for(let i = 0; i < n; i++) {
        arr.push(str);
    }
    return arr.join('');
} 

Use fill and join together

Just like we did in the last section, you can use the fill and join methods to achieve the same result. For this example, we’re going to do things a little differently.

We’re going to use the Array(n) method to create an array of n number of pre-defined elements, waiting to be filled with values. This way, we don’t have to waste lines of code and processing power with a for loop.

Then, let’s tag along the fill method, where we send str as an argument. Array(n).fill(str) will create an array of n number of elements and fill each element with the value inside str.

Finally, let’s tag along the join method where the join condition is, as usual, an empty string. Return the final result, and we’re good to go.

const repeatStr = (str, n) => {
    return Array(n).fill(str).join('');
} 

Using just join

As you know, the join method can take any string as a join condition. Why not make it the string we want repeated? That makes everything easy, doesn’t it?

So, let’s use Array(n) to create an array with n number of elements, and tag the join method to it, where the join condition is str, so right after every empty value (which is nothing), we have the value inside str as the connecting set of characters, which will effectively just be str repeated n number of times, as we wanted.

const repeatStr = (str, n) => {
    return Array(n).join(str);
} 

There you go! That was quite a ride. Whew.

We looked at the repeat() method, manually repeating strings, and finally, using array methods in creative ways to arrive at our desired result.

Leave a Comment