Repeating letter string - 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

Then the output should be ?

const output = 'hhooww  aarree  yyoouu'

Example

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

Output

Following is the output in the console ?

hhooww  aarree  yyoouu

Alternative Approach Using map()

You can also use the map() method with array splitting and joining:

const str = 'hello world';

const repeatWithMap = (str, n) => {
    return str.split('').map(char => char.repeat(n)).join('');
};

console.log(repeatWithMap(str, 3));
hhheeellllllooo   wwwooorrrlllddd

How It Works

The String.prototype.repeat() method repeats each character the specified number of times. The function iterates through each character in the original string and builds a new string with repeated characters.

Conclusion

Both approaches effectively repeat each character in a string. The repeat() method provides a clean solution for character repetition in JavaScript strings.

Updated on: 2026-03-15T23:18:59+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements