在JavaScript中生成一个随机的字母数字(大写,小写和数字)字符串来用作可能唯一的标识符的最短方法是什么?


当前回答

随机字符:

String.fromCharCode(i); //where is an int

随机整数:

Math.floor(Math.random()*100);

把它们放在一起:

function randomNum(hi){
    return Math.floor(Math.random()*hi);
} 
function randomChar(){
    return String.fromCharCode(randomNum(100));
}
function randomString(length){
   var str = "";
   for(var i = 0; i < length; ++i){
        str += randomChar();
   }
   return str;
}
var RandomString = randomString(32); //32 length string

小提琴:http://jsfiddle.net/maniator/QZ9J2/

其他回答

如果你只想允许特定的字符,你也可以这样做:

function randomString(length, chars) {
    var result = '';
    for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
    return result;
}
var rString = randomString(32, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');

下面是一个演示的jsfiddle: http://jsfiddle.net/wSQBx/

另一种方法是使用一个特殊的字符串,告诉函数使用什么类型的字符。你可以这样做:

function randomString(length, chars) {
    var mask = '';
    if (chars.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz';
    if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    if (chars.indexOf('#') > -1) mask += '0123456789';
    if (chars.indexOf('!') > -1) mask += '~`!@#$%^&*()_+-={}[]:";\'<>?,./|\\';
    var result = '';
    for (var i = length; i > 0; --i) result += mask[Math.floor(Math.random() * mask.length)];
    return result;
}

console.log(randomString(16, 'aA'));
console.log(randomString(32, '#aA'));
console.log(randomString(64, '#A!'));

小提琴:http://jsfiddle.net/wSQBx/2/

或者,像下面描述的那样使用base36方法,你可以这样做:

function randomString(length) {
    return Math.round((Math.pow(36, length + 1) - Math.random() * Math.pow(36, length))).toString(36).slice(1);
}

当我看到这个问题时,我想到了我必须生成uuid的时候。我不能把代码的功劳,因为我确信我在stackoverflow上找到了它。如果你不想在字符串中使用破折号,那就去掉破折号。函数如下:

function generateUUID() {
    var d = new Date().getTime();
    var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,function(c) {
        var r = (d + Math.random()*16)%16 | 0;
        d = Math.floor(d/16);
        return (c=='x' ? r : (r&0x7|0x8)).toString(16);
    });
    return uuid.toUpperCase();
}

小提琴:http://jsfiddle.net/nlviands/fNPvf/11227/

beans建议的另一种答案变体

(Math.random()*1e32).toString(36)

通过改变乘数1e32,你可以改变随机字符串的长度。

使用md5库:https://github.com/blueimp/JavaScript-MD5

最短的方法:

md5(随机数学。()

如果你想限制大小为5:

md5 (math . random())。substr (0, 5)

我只是发现了一个非常好的优雅的解决方案:

Math.random().toString(36).slice(2)

这个实现的注意事项:

This will produce a string anywhere between zero and 12 characters long, usually 11 characters, due to the fact that floating point stringification removes trailing zeros. It won't generate capital letters, only lower-case and numbers. Because the randomness comes from Math.random(), the output may be predictable and therefore not necessarily unique. Even assuming an ideal implementation, the output has at most 52 bits of entropy, which means you can expect a duplicate after around 70M strings generated.