Computer >> Computer tutorials >  >> Programming >> Javascript

Repeating string for specific number of times using JavaScript


Problem

We are required to write a JavaScript function that takes in a string and a number as two arguments.

Our function should repeat the input string the number of times specified by the second argument and return the new repeating string.

Example

Following is the code −

const str = 'this';
const num = 8;
const repeatSpecificTimes = (str = '', num = 1) => {
   const arr = [str];
   let i = 1;
   while(i < num){
      arr.push(arr[0]);
      i++;
   };
   return arr.join('');
};
console.log(repeatSpecificTimes(str, num));

Output

thisthisthisthisthisthisthisthis