我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
当前回答
一个衬垫[a-z]:
String.fromCharCode(97 + Math.floor(Math.random() * 26))
其他回答
这是firefoxchrome代码(插件等)
它可以节省你几个小时的研究时间。
function randomBytes( amount )
{
let bytes = Cc[ '@mozilla.org/security/random-generator;1' ]
.getService ( Ci.nsIRandomGenerator )
.generateRandomBytes( amount, '' )
return bytes.reduce( bytes2Number )
function bytes2Number( previousValue, currentValue, index, array )
{
return Math.pow( 256, index ) * currentValue + previousValue
}
}
将其用作:
let strlen = 5
, radix = 36
, filename = randomBytes( strlen ).toString( radix ).splice( - strlen )
这一个结合了许多给出的答案。
var randNo=Math.floor(Math.random()*100)+2+“”+new Date().getTime()+Math.floof(Math.rrandom()*100)+2+(Math.rand().toString(36).replace(/[^a-zA-Z]+/g,'').substr(0,5));console.log(randNo);
我用了一个月,效果很好。
这里有一些简单的一行。更改新阵列(5)以设置长度。
包括0-9a-z
new Array(5).join().replace(/(.|$)/g, function(){return ((Math.random()*36)|0).toString(36);})
包括0-9a-zA-Z
new Array(5).join().replace(/(.|$)/g, function(){return ((Math.random()*36)|0).toString(36)[Math.random()<.5?"toString":"toUpperCase"]();});
ES6编码(0-9a-z)
Array(5).fill().map(n=>(Math.random()*36|0).toString(36)).join('')
这是我的方法(使用TypeScript)。
我决定写另一个响应,因为我没有看到任何使用现代js和干净代码的简单解决方案。
const DEFAULT_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
function getRandomCharFromAlphabet(alphabet: string): string {
return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
}
function generateId(idDesiredLength: number, alphabet = DEFAULT_ALPHABET): string {
/**
* Create n-long array and map it to random chars from given alphabet.
* Then join individual chars as string
*/
return Array.from({length: idDesiredLength}).map(() => {
return getRandomCharFromAlphabet(alphabet);
}).join('');
}
generateId(5); // jNVv7
function generateRandomStringLettersAndNumbers(maxLength): string {
return crypto.randomBytes(maxLength).toString('hex').substring(0, maxLength);
}