Sat Oct 09 2021·2 min read
Photo by Katarzyna Grabowska
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
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.
repeat method is not supported in Internet Explorer, if you have to
support the browser, you can add a
for it, use babel to compile your code to an older
To create a string of variable length:
Array()constructor to create an array of empty elements with length N + 1
join()method on the array to join the elements with the string you want to repeat
joinmethod 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
method to join the array elements by the specific string.
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.
I'll send you 1 email a week with links to all of the articles I've written that week