Skip to content

Latest commit

 

History

History
32 lines (22 loc) · 971 Bytes

File metadata and controls

32 lines (22 loc) · 971 Bytes

A character or a set of characters can be repeated multiple times in JavaScript using the following trick:

Array(n).join(string);

What we are doing here is creating a new Array with n undefined elements, and then joining them using string. Note that because the string is inserted only between the array elements, this leaves us with n-1 repeats of the string.

Example:

var newString = Array(4).join('abc');

console.log(newString);
// 'abcabcabc'

Alternatively, you could also use the fill() method to achieve the same result:

newString = Array(4).fill('abc').join('');

Finally, in ES6 there is now a repeat() method available:

str.repeat(count);

console.log('abc'.repeat(3));
// 'abcabcabc'