How to use String.prototype.repeat() In Javascript
- Here, we select a random character from the given character set and use the repeat() method to repeat it the desired number of times.
- Create a characters array containing all the characters that you allow to be in your string.
- Generate a random index using Math.random() and store it in a variable.
- Select the character present at previously generated random index from your character array. And use repeat() method to repeat the character “n” times.
Example: This example shows the use of the above-explained approach.
function getString(n) {
const characters =
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
const charLen = characters.length;
// Generating a random index
const idx = Math.floor(Math.random() * charLen);
// Using above generated random index
// and extracting the corresponding
// character from "characters" array
const ch = characters.charAt(idx);
// Using repeat method to repeat
// the character "n" times.
return ch.repeat(n);
}
const result = getString(10);
console.log(result);
Output
QQQQQQQQQQ
JavaScript Program for Generating a String of Specific Length
In this article, we are going to discuss how can we generate a string having a specific length. You might encounter many situations when working with JavaScript where you need to produce a string with a specified length. This could be done for a number of reasons, including generating passwords, unique IDs, or formatting data for display.
Table of Content
- Using For Loop
- Using String.prototype.repeat()
- Using Array Manipulation
- Using Array.from()
- Using Crypto Module