我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
当前回答
我已经制作了一个字符串原型,它可以生成一个给定长度的随机字符串。
如果你想要特殊字符,你也可以解密,你可以避免一些。
/**
* STRING PROTOTYPE RANDOM GENERATOR
* Used to generate a random string
* @param {Boolean} specialChars
* @param {Number} length
* @param {String} avoidChars
*/
String.prototype.randomGenerator = function (specialChars = false, length = 1, avoidChars = '') {
let _pattern = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
_pattern += specialChars === true ? '(){}[]+-*/=' : '';
if (avoidChars && avoidChars.length) {
for (let char of avoidChars) {
_pattern = _pattern.replace(char, '');
}
}
let _random = '';
for (let element of new Array(parseInt(length))) {
_random += _pattern.charAt(Math.floor(Math.random() * _pattern.length));
}
return _random;
};
您可以这样使用:
// Generate password with specialChars which contains 10 chars and avoid iIlL chars
var password = String().randomGenerator(true, 10, 'iIlL');
希望有帮助。
其他回答
如果您无法键入字符集,使用String.fromCharCode和范围内的Math.random可以在任何Unicode代码点范围内创建随机字符串。例如,如果您想要17个随机藏文字符,可以输入ranstr(17,0xf00,0xfff),其中(0xf00,0xff)对应于藏文Unicode块。在我的实现中,如果不指定代码点范围,生成器将输出ASCII文本。函数ranchar(a,b){a=(a==未定义?0:a);b=(b===未定义?127:b);return String.fromCharCode(Math.floor(Math.random()*(b-a)+a));}函数transtr(len,a,b){a=a||32;var结果=“”;对于(var i=0;i<len;i++){结果+=ranchar(a,b)}返回结果;}//以下是随机Unicode块的一些示例console.log('拉丁语基本块:'+transtr(10,0x000,0x007f))console.log('拉丁语-1增补块:'+transtr(10,0x080,0x0ff))console.log('货币符号块中:'+transtr(10,0x20a0,0x20cf))console.log('在类字母符号块中:'+transtr(10,0x2100,0x214f))console.log('在Dingbats块中:'+transtr(10,0x2700,0x27bf))
最紧凑的解决方案,因为切片比子字符串短。从字符串末尾减去允许避免由随机函数生成的浮点符号:
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));
生成安全的随机字母数字Base-62字符串:
函数生成UID(长度){return window.btoa(String.fromCharCode(…window.crypto.getRandomValues(新Uint8Array(长度*2))).replace(/[+/]/g,“”).substring(0,长度);}console.log(生成UID(22));//“yFg3Upv2cE9cKOXd7hHwWp”console.log(生成UID(5));//“YQGzP”
我知道每个人都已经做好了,但我想以最轻量级的方式(轻代码,而不是CPU)尝试一下:
函数rand(长度,电流){电流=电流?当前:“”;返回长度?rand(--length,“0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvxyz”.charAt(Math.floor(Math.random()*60))+电流):电流;}console.log(rand(5));
这需要一点时间来理解,但我认为它确实显示了javascript的语法是多么棒。
您可以使用base64:
function randomString(length)
{
var rtn = "";
do {
rtn += btoa("" + Math.floor(Math.random() * 100000)).substring(0, length);
}
while(rtn.length < length);
return rtn;
}