Generating random string of specified length in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in a number n and returns a random string of length n containing no other than the 26 English lowercase alphabets.

Therefore, let’s write the code for this function −

Example

The code for this will be −

const num = 8;
const randomNameGenerator = num => {
   let res = '';
   for(let i = 0; i < num; i++){
      const random = Math.floor(Math.random() * 27);
      res += String.fromCharCode(97 + random);
   };
   return res;
};
console.log(randomNameGenerator(num));

Output

The output in the console will be −

kdcwping

Note − This is one of many possible outputs. Console output is expected to differ every time.

raja
Published on 19-Oct-2020 10:20:04
Advertisements