Generating random string with a specific length in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in a number as one and the only argument. The function should then return a randomly generated string of the length specified by the argument.

The character set to be used for the string generation should only contain uppercase and lowercase alphabets (no whitespaces, punctuations or numerals).

Example

The code for this will be −

const num = 13;
const randomString = (len = 1) => {
   const charSet =
   'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
   let randomString = '';
   for (let i = 0; i < len; i++) {
      let randomPoz = Math.floor(Math.random() * charSet.length);
      randomString += charSet.substring(randomPoz,randomPoz+1);
   };
   return randomString;
};
console.log(randomString(num));

Output

And the output in the console will be −

EqprjcudAhmVg

The output is likely to differ in each run.

raja
Published on 21-Nov-2020 10:07:20
Advertisements