How to Repeat a String n Times in Javascript

In this tutorial, you will learn how to repeat a string n times in javascript. As a newbie, it could be a bit tricky for you, but as a web developer, you should be aware of how to do so.

There are numerous ways to repeat a string multiple times but we are going to make use of the simplest approach and that is by using the repeat() method.

In the following example, we have one global string. We will pass it to our custom method to repeat it a certain number of times and later we will log the final string in the console window.  Please have a look over the code example and the steps given below.

HTML & CSS

  • We do not have any element in the HTML file because it is not required for this tutorial.
  • We have only included our javascript file script.js with a script tag at the bottom. The javascript code will run as soon as the page is loaded in the browser.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    
    <script src="script.js"></script>
</body>
</html>

Javascript

  • We have created a custom method repeatString() which takes a string and a number as parameters.
  • In the repeatString() method, we are using the Math.abs() method to convert the value of times into an absolute number because if we pass a negative number as a second parameter, then this function will throw an error and we do not want that.
  • We are calling the repeat() method and passing times variable as a parameter. This method will repeat the string depending upon the value of the times variable and return it.
  • We are calling the repeatString() method and passing it a string “Hello World” and -4 as a parameter. As a result, the string will be repeated 4 times.
  • We are storing the returned value in the result variable and logging it in the console window by using the console.log() method.
function repeatString(msg, times){
    times = Math.abs(times);    
    return msg.repeat(times);
}

const result = repeatString('Hello World', 4);
console.log(result);