Member-only story
Get random string in JavaScript
For more questions and answers visit our website at Frontend Interview Questions
Basic Random String Generation
A random string can be created by selecting random characters from a set of allowed characters. This can be achieved using JavaScript’s Math.random() function in combination with a predefined character set.
Example: Basic Random String Generation
function getRandomString(length) {
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let result = '';
const charactersLength = characters.length;
for (let i = 0; i < length; i++) {
const randomIndex = Math.floor(Math.random() * charactersLength);
result += characters.charAt(randomIndex);
}
return result;
}
const randomString = getRandomString(10);
console.log(randomString); // Outputs a random string like 'aZ3kLmNpQs'Explanation:
- The
getRandomStringfunction takes alengthparameter specifying the length of the random string. - A string of possible characters (
characters) is defined. - A loop runs for the specified length, appending a random character from the
charactersstring to the result. Math.random()generates a random number between 0 and 1…







