Repeating string for specific number of times using JavaScript

JavascriptWeb DevelopmentFront End Technology

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 −

 Live Demo

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
raja
Published on 19-Apr-2021 10:51:23
Advertisements