Create a String of length N filled with repeated char in JS

avatar
Borislav Hadzhiev

Last updated: Dec 21, 2022
2 min

banner

# Create a String of length N filled with repeated char in JS

Use the String.repeat() method to create a string of variable length.

The String.repeat() method takes the string that should be repeated as a parameter and repeats the string the specified number of times.

index.js
const str = 'a'.repeat(3); console.log(str); // ๐Ÿ‘‰๏ธ 'aaa'

create string of length n filled with repeated char

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

index.js
console.log('a'.repeat(3)); // ๐Ÿ‘‰๏ธ aaa console.log('a'.repeat(4)); // ๐Ÿ‘‰๏ธ aaaa console.log('a'.repeat(5)); // ๐Ÿ‘‰๏ธ aaaaa console.log('abc-'.repeat(2)); // ๐Ÿ‘‰๏ธ abc-abc- console.log('abc-'.repeat(3)); // ๐Ÿ‘‰๏ธ abc-abc-abc-
The method returns a new string, containing the specified number of repetitions of the string it was called on.

Alternatively, you can use the Array() constructor.

# Create a String of Variable Length using the Array() constructor

This is a two-step process:

  1. Use the Array() constructor to create an array of empty elements of length N + 1.
  2. Use the join() method to join the array with the string to be repeated.
index.js
const arr = Array(3 + 1); console.log(arr); // ๐Ÿ‘‰๏ธ [ , , , ] const str = arr.join('a'); console.log(str); // ๐Ÿ‘‰๏ธ aaa

create string of variable length using array constructor

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

index.js
const arr = Array(3 + 1); // ๐Ÿ‘‡๏ธ [ <4 empty items> ] console.log(arr); // ๐Ÿ‘‰๏ธ [ , , , ]

The reason I added 1 to the desired length of the array is that we later use the Array.join() method to join the array elements with the specified string as the separator.

index.js
const arr = Array(3 + 1); console.log(arr); // ๐Ÿ‘‰๏ธ [ , , , ] const str = arr.join('a'); console.log(str); // ๐Ÿ‘‰๏ธ aaa
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 Array.join() method.

Our array consists of 4 empty elements, so the string we passed to the Array.join() method gets repeated 3 times.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.

Copyright ยฉ 2023 Borislav Hadzhiev