Create a String of Variable Length in JavaScript

avatar

Borislav Hadzhiev

Sat Oct 09 20212 min read

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.

index.js
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
index.js
// 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.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee