EN
JavaScript - generate random string of size n characters
3
points
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