Repeating Strings in JavaScript

Josh Sherman
1 min read
Software Development JavaScript

While cleaning up some of my old notes today, specifically stuff I jotted down that would make for a good blog topic, I happened upon the topic of repeating strings in JavaScript.

Things are really easy in ES6+, but if you happen to still support Internet Explorer for some crazy reason, or just want to slum it like it’s the good ol’ days, we can repeat strings by way of a loop:

function repeat(string, repeats) {
  let repeated = ''

  for (let i = 0; i < repeats; i += 1) {
    repeated += string;
  }

  return repeated;
}

repeat('Testing', 100);

Not the most elegant thing in the world, and could probably golf it down a bit.

But, since we’re living in an ES6 world, there’s no reason to spin our wheels on that, and can simply leveraged String.prototype.repeat which accepts a single argument to tell it how many times to repeat.

The aforementioned old school example can be expressed as such:

'Testing'.repeat(100);

And we can call it a day!

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Engineering Manager and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.

Currently Reading

Parasie Eve

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles