How to Repeat a String in JavaScript ?
Last Updated :
02 Apr, 2024
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:
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.
JavaScript
const str = "Gfg ";
const repeatedStr = str.repeat(3);
console.log(repeatedStr);
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.
JavaScript
function repeatString(str, count) {
let result = '';
for (let i = 0; i < count; i++) {
result += str;
}
return result;
}
console.log(repeatString('hello gfg ', 3));
Outputhello 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.
JavaScript
const str = "javascript ";
const repeatedStr = new Array(3).fill(str).join('');
console.log(repeatedStr);
Outputjavascript javascript javascript
Share your thoughts in the comments
Please Login to comment...