Languages
[Edit]
EN

JavaScript - generate random string of size n characters

3 points
Created by:
Dirask Community
6240

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

  1. The first step we need to do is create a variable from which we will draw characters to a random string. In our case it's alphabet variable.
  2. Then we add letters from the alphabet one by one until we reach given length.

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)

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