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

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


当前回答

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

其他回答

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

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

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

希望有帮助。

这里有一种不同的方法,按基数固定长度,不使用RegExp替换lack(基于@bendytree的答案);

function rand(base) {
    // default base 10
    base = (base >= 2 && base <= 36) ? base : 10;
    for (var i = 0, ret = []; i < base; i++) {
        ret[i] = ((Math.random() * base) | 0).toString(base)
            // include 0-9a-zA-Z?
            // [Math.random() < .5 ? 'toString' : 'toUpperCase']();
    }
    return ret.join('');
}
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.

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

您可以使用base64:

function randomString(length)
{
    var rtn = "";

    do {
        rtn += btoa("" + Math.floor(Math.random() * 100000)).substring(0, length);
    }
    while(rtn.length < length);

    return rtn;
}