How to Multiply a String in JavaScript

Updated onbyAlan Morel
How to Multiply a String in JavaScript

JavaScript makes string manipulation very easy because of all the built-in functions.

One of the most common string manipulation tasks is to repeat a string a certain number of times.

In this post, we'll look at the three best ways to multiply a string in JavaScript.

Using the String.repeat() Method

The most straightforward way to multiply a string is to use the repeat() method on the String class.

The repeat() method takes a number as an argument and returns a new string that is the original string repeated that many times.

First, let's start with the string we want to repeat:

const string = "Hello";

Now, let's use the repeat() method to repeat the string 3 times:

const string = "Hello";

const repeatedString = string.repeat(3);

console.log(repeatedString);
HelloHelloHello

Because it accepts any number as the argument, instead of passing an exact value directly, you can just pass it a variable:

const string = "Hello";

const times = 3;
const repeatedString = string.repeat(times);

console.log(repeatedString);
HelloHelloHello

Using a for loop

Rather than using a built-in function, you can also just mimic the same behavior using a for loop.

First, let's start with the string we want to repeat:

const string = "Hello";

Now, let's use a for loop to repeat the string 3 times:

const string = "Hello";

let repeatedString = "";
for (let i = 0; i < 3; i++) {
    repeatedString += string;
}
console.log(repeatedString);
HelloHelloHello

This can be useful if you want any custom behavior, such as adding a separator between each repetition:

const string = "Hello";

let repeatedString = "";
for (let i = 0; i < 3; i++) {
    repeatedString += string;
    if (i < 2) {
        repeatedString += ", ";
    }
}
console.log(repeatedString);
Hello, Hello, Hello

Using a while loop

Similar to using a for loop, you can also use a while loop to repeat a string.

Like before, we can start with the string we want to repeat:

const string = "Hello";

Then we can use a while loop to loop until a counter hits the number of times we want to repeat the string:

const string = "Hello";

let repeatedString = "";
let i = 0;
let repeat = 3;

while (i < repeat) {
    repeatedString += string;
    i++;
}
console.log(repeatedString);

This has the same pros and cons as the for loop example since you have full control over the behavior at the expense of longer code.

Conclusion

In this post, we looked at three ways to multiply a string in JavaScript.

Your options are to use the built-in repeat() method, use a for loop, or use a while loop.

Thanks for reading!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.