Suppose I have a list of strings. How do I generate a random one?
You mean, get a random array member?
var strings = ['a', 'b', 'c'];
var randomIndex = Math.floor(Math.random() * strings.length);
var randomString = strings[randomIndex];
See it on jsFiddle.
If you mean a random string, it is a little different.
var randomStrLength = 16,
pool = 'abcdefghijklmnopqrstuvwxyz0123456789',
randomStr = '';
for (var i = 0; i < randomStrLength; i++) {
var randomChar = pool.charAt(Math.floor(Math.random() * pool.length));
randomStr += randomChar;
}
See it on jsFiddle.
Of course, you can skip the pool
variable and do String.fromCharCode()
with a random number between 97 ('a'.charCodeAt(0)
) and 122 ('z'.charCodeAt(0)
) for lowercase letters, etc. But depending on the range you want (lowercase and uppercase, plus special characters), using a pool is less complex.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With