Languages
[Edit]
EN

JavaScript - generate random string of size n characters

3 points
Created by:
Brandy-Mccabe
724

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(alphabet.length * Math.random())];
    }
    return result;
}


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

 

References

  1. Math.random() - MDN Web Docs 
  2. Math.floor() - MDN Web Docs
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Cross technology - 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