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:
xxxxxxxxxx
1
var alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
2
3
function randomString(length) {
4
var result = '';
5
for (var i = 0; i < length; ++i) {
6
result += alphabet[Math.floor(alphabet.length * Math.random())];
7
}
8
return result;
9
}
10
11
12
// Usage example:
13
// // Example random strings:
14
console.log(randomString(5)); // VhMsQ
15
console.log(randomString(10)); // eVOznvSxWw
16
console.log(randomString(20)); // ZZomN9sxyaL9vfsGE3to