我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。

用JavaScript实现这一点的最佳方法是什么?


当前回答

生成安全的随机字母数字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”

其他回答

我已经制作了一个字符串原型,它可以生成一个给定长度的随机字符串。

如果你想要特殊字符,你也可以解密,你可以避免一些。

/**
 * 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');

希望有帮助。

最紧凑的解决方案,因为切片比子字符串短。从字符串末尾减去允许避免由随机函数生成的浮点符号:

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));

这是肯定的

<script language="javascript" type="text/javascript">
function randomString() {
 var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
 var string_length = 8;
 var randomstring = '';
 for (var i=0; i<string_length; i++) {
  var rnum = Math.floor(Math.random() * chars.length);
  randomstring += chars.substring(rnum,rnum+1);
 }
 document.randform.randomfield.value = randomstring;
}
</script>

我使用var randId='rand'+new Date().getTime();

为了满足要求[a-zA-Z0-9]和5个字符的长度,使用

对于浏览器:

btoa(Math.random().toString()).substring(10,15);

对于NodeJS:

Buffer.from(Math.random().toString()).toString("base64").substring(10,15);

将出现小写字母、大写字母和数字。

(字体兼容)