Create a String of Variable Length in JavaScript


Borislav Hadzhiev

Last updated: Oct 9, 2021


Photo from Unsplash

Create a String of Variable Length #

To create a string of variable length, use the repeat() method. The method takes the number, the string should be repeated as a parameter, e.g. 'abc'.repeat(3) repeats the string 3 times and returns a new, concatenated string.

const str = 'a'.repeat(3); console.log(str); // 👉️ 'aaa'

The parameter we pass to the String.repeat method is the number of times the string should be repeated.

The method returns a new string, containing the specified number of repetitions of the string it was called on.

The repeat method is not supported in Internet Explorer, if you have to support the browser, you can add a polyfill for it, use babel to compile your code to an older version of JavaScript or use the next approach shown in this article.

To create a string of variable length:

  1. Use the Array() constructor to create an array of empty elements with length N + 1
  2. Call the join() method on the array to join the elements with the string you want to repeat
  3. The join method returns a new string, where the array elements are separated by the specified string
// Supported in IE 6-11 const arr = Array(3 + 1); console.log(arr); // 👉️ [ , , , ] const str = arr.join('a'); console.log(str); // 👉️ aaa

We use the Array constructor to create an array, filled with 4 empty elements.

The reason I add 1 to the desired length of the array is because we later use the Array.join method to join the array elements by the specific string.

An easy way to think about it is - the number of commas in the array is how many repetitions you'll get when you call the join method.

Since our array consists of 4 empty elements, the only output we can expect is the separator we use to join the array elements, repeated 3 times.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.