我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
当前回答
最紧凑的解决方案,因为切片比子字符串短。从字符串末尾减去允许避免由随机函数生成的浮点符号:
Math.random().toString(36).slice(-5);
甚至
(+new Date).toString(36).slice(-5);
更新:添加了一种使用btoa方法的方法:
btoa(Math.random()).slice(0, 5);
btoa(+new Date).slice(-7, -2);
btoa(+new Date).substr(-7, 5);
//使用Math.random和Base 36:console.log(Math.random().toString(36).slice(-5));//使用新的日期和基数36:console.log((+new Date).toString(36).slice(-5));//使用Math.random和Base 64(btoa):console.log(btoa(Math.random()).slice(0,5));//使用新的日期和基数64(btoa):console.log(btoa(+新日期).slice(-7,-2));console.log(btoa(+新日期).substr(-7,5));
其他回答
在下面的代码中,我正在生成8个字符的随机代码
function RandomUnique(){
var charBank = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012346789";
var random= '';
var howmanycharacters = 8;
for (var i = 0; i < howmanycharacters ; i++) {
random+= charBank[parseInt(Math.random() * charBank.lenght)];
}
return random;
}
var random = RandomUnique();
console.log(random);
递归解决方案:
function generateRamdomId (seedStr) {
const len = seedStr.length
console.log('possibleStr', seedStr , ' len ', len)
if(len <= 1){
return seedStr
}
const randomValidIndex = Math.floor(Math.random() * len)
const randomChar = seedStr[randomValidIndex]
const chunk1 = seedStr.slice(0, randomValidIndex)
const chunk2 = seedStr.slice(randomValidIndex +1)
const possibleStrWithoutRandomChar = chunk1.concat(chunk2)
return randomChar + generateRamdomId(possibleStrWithoutRandomChar)
}
你可以用你想要的种子,如果你不想,不要重复字符。实例
generateRandomId("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")
如果您使用的是Lodash或Undercore,那么非常简单:
var randomVal = _.sample('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', 5).join('');
生成10个字符长的字符串。长度由参数设置(默认值为10)。
function random_string_generator(len) {
var len = len || 10;
var str = '';
var i = 0;
for(i=0; i<len; i++) {
switch(Math.floor(Math.random()*3+1)) {
case 1: // digit
str += (Math.floor(Math.random()*9)).toString();
break;
case 2: // small letter
str += String.fromCharCode(Math.floor(Math.random()*26) + 97); //'a'.charCodeAt(0));
break;
case 3: // big letter
str += String.fromCharCode(Math.floor(Math.random()*26) + 65); //'A'.charCodeAt(0));
break;
default:
break;
}
}
return str;
}
函数randomstring(L){var s=“”;var randomchar=函数(){var n=数学地板(Math.random()*62);如果(n<10)返回n//1-10如果(n<36)返回String.fromCharCode(n+55)//A-Z型return String.fromCharCode(n+61)//a-z型}而(s.length<L)s+=randomchar();返回s;}console.log(随机字符串(5));