-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?

0

2 Answers 2

2

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);

Sign up to request clarification or add additional context in comments.

Comments

1

You can use string.repeat(count):

console.log("#".repeat(5));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.