How to repeat a string in JavaScript?

JavascriptObject Oriented ProgrammingFront End Technology

There are two ways to repeat a string in javascript. One way is to use string.repeat() method and the other way is to use the fill() method. Let's discuss them in detail.

syntax

string.repeat(number);

This method takes a number as a parameter and repeats the string those many numbers of times.

syntax

Array(number).fill(string).join('');

This method initially takes a number and allocates those many numbers of spaces. It inserts the provided string in all those places and joins them to get a repeated string.

Example

In the following example, number 3 is sent into the repeat method as an argument. So the string is repeated for 3 times as shown in the output.

Live Demo

<html>
<body>
<script>
   const str = 'Tutorix, '
   var res = str.repeat(3);
   document.write(res);
</script>
</body>
</html>

Output

Tutorix, Tutorix, Tutorix,


Example

In the following example, Initially, an array is created with 3 slots and the provided string is kept in all those slots and later on, using join() method the elements in the array were joined and the output is displayed as shown.

Live Demo

<html>
<body>
<script>
   const str = 'Tutorialspoint '
   var d = Array(3).fill(str).join('')
   document.write(d);
</script>
</body>
</html>

Output

Tutorialspoint Tutorialspoint Tutorialspoint
raja
Published on 17-Jul-2019 08:52:19
Advertisements