Repeating Strings in 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!

Josh Sherman - The Man, The Myth, The Avatar

About Josh

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


If you found this article helpful, please consider buying me a coffee.