Last updated: Mar 1, 2024
Reading timeยท2 min
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.
const str = 'a'.repeat(3); console.log(str); // ๐๏ธ 'aaa'
The argument we passed to the String.repeat() method is the number of times the string should be repeated.
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-
Alternatively, you can use the Array()
constructor.
This is a two-step process:
Array()
constructor to create an array of empty elements of length
N + 1.join()
method to join the array with the string to be repeated.const arr = Array(3 + 1); console.log(arr); // ๐๏ธ [ , , , ] const str = arr.join('a'); console.log(str); // ๐๏ธ aaa
We used the Array
constructor to create an array, filled with 4 empty
elements.
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.
const arr = Array(3 + 1); console.log(arr); // ๐๏ธ [ , , , ] const str = arr.join('a'); console.log(str); // ๐๏ธ aaa
Array.join()
method.Our array consists of 4 empty elements, so the string we passed to the
Array.join()
method gets repeated 3 times.
You can learn more about the related topics by checking out the following tutorials: