Repeating letter string - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in a string and a number, say n, and the function should return a new string in which all the letters of the original string are repeated n times.

For example: If the string is −

const str = 'how are you'

And the number n is 2

Then the output should be −

const output = 'hhooww  aarree  yyoouu'


Following is the code −

const str = 'how are you';
const repeatNTimes = (str, n) => {
   let res = '';
   for(let i = 0; i < str.length; i++){
      // using the String.prototype.repeat() function
      res += str[i].repeat(n);
   return res;
console.log(repeatNTimes(str, 2));


Following is the output in the console −

hhooww  aarree  yyoouu
Published on 16-Sep-2020 13:37:56