How to Repeat a String in JavaScript ?
The javascript string is an object that represents a sequence of characters. We are going to learn how can we repeat a string using JavaScript.
Below are the methods to repeat a string in JavaScript:
Table of Content
Using the repeat() method
This method is used to create a new string by repeating an existing string a specified number of times using the repeat() method. If a user provides the count to be 0 or negative, then an empty string is returned.
Syntax:
str.repeat(count);
// Here str is your string
// And count is how many times you want to repeat the string
Example: This example shows the implementation of the above-explained approach.
const str = "Gfg ";
const repeatedStr = str.repeat(3);
console.log(repeatedStr);
Output
Gfg Gfg Gfg
Using for Loop
At first define a function "repeatString" and inside a funcrtion define a for loop which repeats a given string a specified number of times.
Syntax:
for (i = 0; i < Number_of_time ; i++) {
ans += Your_String;
}
Example: Below example shows the implementation of the above-explained approach.
function repeatString(str, count) {
let result = '';
for (let i = 0; i < count; i++) {
result += str;
}
return result;
}
console.log(repeatString('hello gfg ', 3));
Output
hello gfg hello gfg hello gfg
Using the Array constructor and join() method
First define a string which you want to repeat. Then use the Array constructor to create an array with a specified length, where each element will represent a repetition of the original string. After that use the fill() method to fill each element in the array with the original string. Then use the join() method to concatenate all the elements of the array into a single string. At last display the string.
Example: This example shows the implementation of the above-explained approach.
const str = "javascript ";
const repeatedStr = new Array(3).fill(str).join('');
console.log(repeatedStr);
Output
javascript javascript javascript
Using Recursion
In this approach, we use recursion to repeat a string a specified number of times. The function calls itself with a decremented count until the base case is reached, at which point it returns the concatenated string.
Example: This example shows the implementation of repeating a string using recursion.
function repeatString(str, count) {
if (count <= 0) {
return '';
}
if (count === 1) {
return str;
}
return str + repeatString(str, count - 1);
}
// Example usage
const originalString = "hello ";
const times = 3;
const result = repeatString(originalString, times);
console.log(result); // Output: "hello hello hello "
Output
hello hello hello