Algorithm


  1. Define Function:

    • Start by defining a function, let's call it generateRandomString.
  2. Specify Parameters:

    • Decide if you want to take any parameters for the length or character set of the random string.
  3. Set Default Values:

    • If parameters are provided, set default values. For example, if no length is specified, default to a certain length.
  4. Define Character Set:

    • Create a character set from which the random string will be generated. This can include uppercase letters, lowercase letters, numbers, and special characters, depending on your requirements.
  5. Initialize Empty String:

    • Create an empty string variable to store the generated random string.
  6. Loop for Desired Length:

    • Use a loop to iterate for the desired length of the random string.
  7. Randomly Select Character:

    • Inside the loop, generate a random index to select a character from the character set.
  8. Append Character to String:

    • Append the selected character to the random string.
  9. Return the Result:

    • After the loop, return the generated random string.

 

Code Examples

#1 Code Example- Generate Random Strings

Code - Javascript Programming

// program to generate random strings

// declare all characters
const characters ='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

function generateString(length) {
    let result = ' ';
    const charactersLength = characters.length;
    for ( let i = 0; i  <  length; i++ ) {
        result += characters.charAt(Math.floor(Math.random() * charactersLength));
    }

    return result;
}

console.log(generateString(5));
Copy The Code & Try With Live Editor

Output

x
+
cmd
B5cgH

#2 Code Example- Generate Random Strings Using Built-in Methods

Code - Javascript Programming

// program to generate random strings

const result = Math.random().toString(36).substring(2,7);
console.log(result);
Copy The Code & Try With Live Editor

Output

x
+
cmd
gyjvo
Advertisements

Demonstration


JavaScript Programing to Generate Random String-DevsEnv

Previous
JavaScript Practice Example #3 - Assign 3 Variables and Print Good Way