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
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.
Example: The example below shows how to generate random characters and numbers in a String using Math. random() and CharAt().
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
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.
Example: The example below shows how to generate random characters and numbers.
// Function to generate a random number within a specified range
function Number_random(min, max) {
console.log("Random Number")
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(Number_random(1, 100));
// Function to generate a random character
function Char_random() {
// Generate between 97 and 122 (ASCII for lowercase letters)
const Numtostr = Math.floor(Math.random() * 26) + 97;
console.log("Random Character")
return String.fromCharCode(Numtostr);
}
console.log(Char_random());
Output
Random Number 53 Random Character p
Contact Us