在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/

其他回答

或者根据Jar Jar的建议,这是我在最近的一个项目中使用的方法(以克服长度限制):

var randomString = function (len, bits)
{
    bits = bits || 36;
    var outStr = "", newStr;
    while (outStr.length < len)
    {
        newStr = Math.random().toString(bits).slice(2);
        outStr += newStr.slice(0, Math.min(newStr.length, (len - outStr.length)));
    }
    return outStr.toUpperCase();
};

Use:

randomString(12, 16); // 12 hexadecimal characters
randomString(200); // 200 alphanumeric characters

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

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.

我使用@Nimphious优秀的第二种方法,发现偶尔返回的字符串是数字-而不是字母数字。 我使用的解决方案是测试使用!isNaN,并再次使用递归调用该函数。 何苦呢?我使用这个函数来创建对象键,如果所有的键都是字母数字,那么所有的键都可以正常排序,但如果你使用 数字作为键与字母数字(字符串)混合在一起循环遍历对象将产生与原始顺序不同的顺序。

function newRandomString(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 += '0123456789';

  var result = '';
  for (var i = length; i > 0; --i) result += mask[Math.floor(Math.random() * 
  mask.length)];
  /*    
        we need a string not a number !isNaN(result)) will return true if '1234' or '3E77'
        because if we're looping through object keys (created by newRandomString()) and 
        a number is used and all the other keys are strings then the number will 
        be first even if it was the 2nd or third key in object
  */
  //use recursion to try again
  if(!isNaN(result)){
    console.log('found a number....:'+result);
    return newRandomString(length, chars)
  }else{
    return result;
  }
};

var i=0;
while (i < 1000) {
  var a = newRandomString(4, '#$aA');
  console.log(i+' - '+a);
  //now we're using recursion this won't occur
  if(!isNaN(a)){
    console.log('=============='+i+' - '+a);
  }
  i++;
}

console.log('3E77:'+!isNaN('3E77'));//true
console.log('1234:'+!isNaN('1234'));//true
console.log('ab34:'+!isNaN('ab34'));//false

32个字符:

for(var c = ''; c.length < 32;) c += Math.random().toString(36).substr(2, 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/