我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
当前回答
function generateRandomStringLettersAndNumbers(maxLength): string {
return crypto.randomBytes(maxLength).toString('hex').substring(0, maxLength);
}
其他回答
function randomString (strLength, charSet) {
var result = [];
strLength = strLength || 5;
charSet = charSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
while (strLength--) { // (note, fixed typo)
result.push(charSet.charAt(Math.floor(Math.random() * charSet.length)));
}
return result.join('');
}
这是最干净的了。它也很快,http://jsperf.com/ay-random-string.
这不是一个完美的解决方案,但它应该奏效。如果出现任何错误,请增加Uint8Array()构造函数中给定的值。此方法的优点是它使用getRandomValues()方法生成加密的强随机值。
var array=新Uint8Array(20);crypto.getRandomValues(数组);var arrayEncoded=btoa(String.fromCharCode(…array)).split(“”);var arrayFiltered=arrayEncoded.filter(值=>{开关(值){大小写“+”:return false;大小写“/”:return false;case“=”:return false;违约:返回true;}});var password=arrayFiltered.slice(0,5).join('');console.log(密码);
紧凑型
var array=新Uint8Array(20);crypto.getRandomValues(数组);var password=btoa(String.fromCharCode(…array)).split(“”).filter(值=>{回来['+','/','=']includes(value);}).切片(0,5).连接('');console.log(密码);
这是我用过的。这是一对夫妇的组合。我在循环中使用它,它生成的每个ID都是唯一的。它可能不是5个字符,但它保证是唯一的。
var newId =
"randomid_" +
(Math.random() / +new Date()).toString(36).replace(/[^a-z]+/g, '');
随机数值(最多16位)
/**
* Random numeric value (up to 16 digits)
* @returns {String}
*/
function randomUid () {
return String(Math.floor(Math.random() * 9e15))
}
// randomUid() -> "3676724552601324"
同样基于doubletap的答案,该方法处理任意长度的随机所需字符(仅限小写),并不断生成随机数,直到收集到足够的字符。
function randomChars(len) {
var chars = '';
while (chars.length < len) {
chars += Math.random().toString(36).substring(2);
}
// Remove unnecessary additional characters.
return chars.substring(0, len);
}