![]() |
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() methodThis 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); Example: This example shows the implementation of the above-explained approach.
Output Gfg Gfg Gfg Using for LoopAt 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++) { Example: Below example shows the implementation of the above-explained approach.
Output hello gfg hello gfg hello gfg Using the Array constructor and join() methodFirst 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.
Output javascript javascript javascript Using RecursionIn 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.
Output hello hello hello |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 14 |