-1

Let's say I want to concatenate a certain string, e.g. "#", a certain number of times, e.g. n=5. (the number of times, n, is variable.)

So for n=5, we would get: ##### but for n=2, we would get: ## etc.

Is there a way to do this without using a loop?

Sberk
  • 1
  • 2

2 Answers2

1

You can use string.repeat(count):

console.log("#".repeat(5));
Hamms
  • 5,016
  • 21
  • 28
1

You can do it by using String.prototype.repeat(). According to MDN

The repeat() method constructs and returns a new string which contains the specified number of copies of the string on which it was called, concatenated together.

It takes a count parameter as it's the only argument which is

An integer between 0 and +Infinity, indicating the number of times to repeat the string.

And returns

A new string containing the specified number of copies of the given string.

let str = "#";
let newStr = str.repeat(5);
console.log(newStr);
Sajeeb Ahamed
  • 6,070
  • 2
  • 21
  • 30