Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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 ?
Using String.prototype.repeat()
The most straightforward approach is to iterate through each character and use the built-in repeat() method:
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));
hhooww aarree yyoouu
Using Array Methods
Alternatively, we can use array methods for a more functional approach:
const str = 'how are you';
const repeatNTimes = (str, n) => {
return str.split('').map(char => char.repeat(n)).join('');
};
console.log(repeatNTimes(str, 3));
console.log(repeatNTimes('hello', 2));
hhhooowww aaaarrreee yyyooouuu hheelllloo
Using Manual Loop
For educational purposes, here's how to implement it without using the repeat() method:
const str = 'test';
const repeatNTimes = (str, n) => {
let result = '';
for(let i = 0; i < str.length; i++){
for(let j = 0; j < n; j++){
result += str[i];
}
}
return result;
};
console.log(repeatNTimes(str, 4));
tttteeeesssstttt
Comparison
| Method | Readability | Performance | Use Case |
|---|---|---|---|
repeat() method |
High | Best | Recommended approach |
| Array methods | High | Good | Functional programming style |
| Manual loops | Medium | Fair | Educational/legacy support |
Conclusion
The String.prototype.repeat() method provides the cleanest and most efficient solution for repeating characters in a string. Choose the array method approach when working in a functional programming style.
