Repeat a String in Javascript a Number of Times

Repeat a string in JavaScript a number of times

As a JavaScript developer, you may come across situations where you need to repeat a string a certain number of times. Fortunately, JavaScript provides multiple solutions to achieve this. In this article, we will explore three different approaches to repeat a string in JavaScript.

1. Using a for loop

One way to repeat a string in JavaScript is by using a for loop. By iterating over the desired number of repetitions, we can concatenate the string to a new variable.

function repeatString(str, num) {
  let repeatedString = '';
  
  for (let i = 0; i < num; i++) {
    repeatedString += str;
  }
  
  return repeatedString;
}

console.log(repeatString('Hello', 3));

The above code defines a function repeatString that takes in two parameters: str (the string to be repeated) and num (the number of repetitions). The function initializes an empty string repeatedString and uses a for loop to concatenate the str to repeatedString num times. Finally, the function returns the repeated string.

Output: HelloHelloHello

2. Using the repeat() method

In ES6, JavaScript introduced the repeat() method for strings, which allows us to repeat a string a specified number of times.

const repeatedString = 'Hello'.repeat(3);
console.log(repeatedString);

In the above code, the repeat() method is called on the string 'Hello' with an argument of 3, indicating that the string should be repeated three times.

Output: HelloHelloHello

3. Using the fill() and join() methods

Another approach to repeat a string is by using the fill() and join() methods available for arrays in JavaScript.

const repeatedString = Array(3).fill('Hello').join('');
console.log(repeatedString);

In the above code, we create an array of length 3 using the Array() constructor. We then fill each element of the array with the string 'Hello' using the fill() method. Finally, we join the array elements into a single string using the join('') method with an empty separator.

Output: HelloHelloHello

These are three different ways to repeat a string in JavaScript. Choose the approach that suits your requirements and coding style. Happy coding!


Posted

in

, ,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *