How to use Math.random() and charAt() Method In Javascript

The function Str_Random generates a random string of specified length, combining characters and numbers. It iterates length times, randomly selecting a character from the characters string using the charAt() method, which retrieves the character at a random index generated by Math.random() * characters.length, appending each selected character to the result string, and finally returning the random string.

Example: The example below shows how to generate random characters and numbers in a String using Math. random() and CharAt().

JavaScript
function Str_Random(length) {
    let result = '';
    const characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
    
    // Loop to generate characters for the specified length
    for (let i = 0; i < length; i++) {
        const randomInd = Math.floor(Math.random() * characters.length);
        result += characters.charAt(randomInd);
    }
    return result;
}
console.log(Str_Random(10));

Output
zu0vm9576q

Generate Random Characters & Numbers in JavaScript

Generate random characters and numbers in JavaScript utilizing Math.random for random numbers and String.fromCharCode() for generating random strings. Combining Math.random and ch.charAt() generates a random mix of characters and numbers within a specified range.

Below are the approaches to Generate random characters and numbers in JavaScript:

Table of Content

  • Random mix of characters and numbers in a String
  • Random characters and numbers

Similar Reads

Using Math.random() and charAt() Method

The function Str_Random generates a random string of specified length, combining characters and numbers. It iterates length times, randomly selecting a character from the characters string using the charAt() method, which retrieves the character at a random index generated by Math.random() * characters.length, appending each selected character to the result string, and finally returning the random string....

Using Math.random() and String.fromCharCode()

The Number_random function generates a random number within the specified range using Math.random() and Math.floor(). It logs “Random Number” to the console and returns the generated random number. The Char_random function generates a random lowercase letter by converting a randomly generated number (between 97 and 122) to a character using String.fromCharCode(). It logs “Random Character” to the console and returns the generated random character....

Contact Us