Sitemap

Member-only story

Get random string in JavaScript

3 min readAug 4, 2024

--

Press enter or click to view image in full size
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 getRandomString function takes a length parameter 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 characters string to the result.
  • Math.random() generates a random number between 0 and 1…

--

--

Pravin M
Pravin M

Written by Pravin M

I am a frontend developer with 10+ years of experience Blog :- https://www.frontendinterviewquestions.com