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

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


当前回答

如果您使用的是Lodash或Undercore,那么非常简单:

var randomVal = _.sample('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', 5).join('');

其他回答

如果您无法键入字符集,使用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).substr(2,5)

基于该解决方案,支持小写和大写:

Math.random().toString(36).substr(2,5).split(“”).map(c=>Math.randm()<0.5?c.toUpperCase():c).jjoin(“”);

更改substr(2,5)中的5以调整到所需的长度。

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

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

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

希望有帮助。

一行使用地图,可以完全控制长度和字符。

const rnd = (len, chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') => [...Array(len)].map(() => chars.charAt(Math.floor(Math.random() * chars.length))).join('')

console.log(rnd(12))

简单方法:

function randomString(length) {
    let chars = [], output = '';
    for (let i = 32; i < 127; i ++) {
        chars.push(String.fromCharCode(i));
    }
    for (let i = 0; i < length; i ++) {
        output += chars[Math.floor(Math.random() * chars.length )];
    }
    return output;
}

如果您想要更多或更少的字符,请将“127”更改为其他字符。