How to use Math.random() and String.fromCharCode() In Javascript
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
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