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().
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
Contact Us