Languages
[Edit]
EN

JavaScript - generate random string of size n characters

3 points
Created by:
Brandy-Mccabe
304

In this article, we would like to show you how to generate a random string in JavaScript.

In the below example randrom string is generated using predefined alphabet. The string is generated by seleting random characters from the alphabet.

Runnable example:

// ONLINE-RUNNER:browser;

var alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

function randomString(length) {
   var result  = '';
   for (var i = 0; i < length; ++i) {
      result += alphabet[Math.floor(Math.random() * alphabet.length)];
   }
   return result;
}

//                             // Example random strings:
console.log(randomString(5));  // VhMsQ
console.log(randomString(10)); // eVOznvSxWw
console.log(randomString(20)); // ZZomN9sxyaL9vfsGE3to

References

JavaScript - String (popular problems)

JavaScript - generate random string of size n characters
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join