The n times dribbling strings in JavaScript



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.

Output

Then the output should be −

const output = 'hhooww aarree yyoouu'

Therefore, let’s write the code for this function −

Example

The code for this will be −

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));

The output in the console will be −

hhooww aarree yyoouu
Updated on: 2020-10-17T11:26:15+05:30

105 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements