Here's the code I usually use. The resulting ID is designed to be
human readable, so if that's not a use-case for you then drop the 0/o,
1/l and tailing dash reductions:
/**
* Return a random id that's 9 letters long.
* 24*(24+8+1)^7*(24+8) = 32,730,964,206,336
* @return {string} Random id.
*/
function uniqueId() {
// First character must be a letter (W3 spec for ID).
// Drop 0/o and 1/l since they are visually ambiguous.
var soup = 'abcdefghijkmnpqrstuvwxyz';
var id = soup.charAt(Math.random() * soup.length);
// Subsequent characters may include these.
soup += '23456789-';
for (var x = 1; x < 9; x++) {
id += soup.charAt(Math.random() * soup.length);
}
if (id.indexOf('--') != -1) {
// Don't allow IDs with '--' in them since it might close a
comment.
id = uniqueId();
} else if (id.charAt(id.length - 1) == '-') {
// A dash at the end looks weird.
id = uniqueId();
}
return id;
}
The result is 32,730,964,206,336 permutations. Let's assume that an
attacker can hit the server 100 times per second. That would mean he
could brute-force the entire space in 10,379 years. Is this good
enough for you? :)