Open In App

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.

Using For Loop

Example: This example shows the use of the above-explained approach.






function getString(n) {
    let str = '';
    const characters = 
        'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    const charLen = characters.length;
  
    for (let i = 0; i < n; i++) {
  
        // Generating a random index
        const idx = Math.floor(Math.random() * charLen);
  
        str += characters.charAt(idx);
    }
  
    return str;
}
  
const result = getString(10);
console.log(result);

Output
qPyRFuEHGB

Using String.prototype.repeat()

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

Using Array Manipulation

Example: This example shows the use of the above-explained approach.




function getString(n) {
    const characters = 
        'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    const charLen = characters.length;
  
    const resultArray = [];
  
    for (let i = 0; i < n; i++) {
      
        // Generating a random index 
        const idx = Math.floor(Math.random() * charLen);
  
        // Pushing the corresponding
        //  character to the array
        resultArray.push(characters.charAt(idx));
    }
  
    // Joining all the characters of the array
    return resultArray.join('');
}
  
const result = getString(10);
console.log(result);

Output
QwZMolRRqi

Article Tags :