我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
当前回答
简单方法:
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”更改为其他字符。
其他回答
生成包含aA zZ和0-9字符集合的随机字符串。只需使用长度参数调用此函数。
所以要回答这个问题:generateRandomString(5)
generateRandomString(length){
let result = "", seeds
for(let i = 0; i < length - 1; i++){
//Generate seeds array, that will be the bag from where randomly select generated char
seeds = [
Math.floor(Math.random() * 10) + 48,
Math.floor(Math.random() * 25) + 65,
Math.floor(Math.random() * 25) + 97
]
//Choise randomly from seeds, convert to char and append to result
result += String.fromCharCode(seeds[Math.floor(Math.random() * 3)])
}
return result
}
生成不带数字的字符串的版本:
generateRandomString(length){
let result = "", seeds
for(let i = 0; i < length - 1; i++){
seeds = [
Math.floor(Math.random() * 25) + 65,
Math.floor(Math.random() * 25) + 97
]
result += String.fromCharCode(seeds[Math.floor(Math.random() * 2)])
}
return result
}
为后代发布ES6兼容版本。如果这是多次调用,请确保将.length值存储到常量变量中。
// USAGE:
// RandomString(5);
// RandomString(5, 'all');
// RandomString(5, 'characters', '0123456789');
const RandomString = (length, style = 'frictionless', characters = '') => {
const Styles = {
'all': allCharacters,
'frictionless': frictionless,
'characters': provided
}
let result = '';
const allCharacters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
const frictionless = 'ABCDEFGHJKMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789';
const provided = characters;
const generate = (set) => {
return set.charAt(Math.floor(Math.random() * set.length));
};
for ( let i = 0; i < length; i++ ) {
switch(Styles[style]) {
case Styles.all:
result += generate(allCharacters);
break;
case Styles.frictionless:
result += generate(frictionless);
break;
case Styles.characters:
result += generate(provided);
break;
}
}
return result;
}
export default RandomString;
"12345".split('').map(function(){return 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'.charAt(Math.floor(62*Math.random()));}).join('');
//or
String.prototype.rand = function() {return this.split('').map(function(){return 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'.charAt(Math.floor(62*Math.random()));}).join('');};
将生成长度为第一个/调用字符串的随机字母数字字符串
随机字符串生成器(字母数字|字母数字|数字)
/***伪随机串发生器* http://stackoverflow.com/a/27872144/383904*默认值:返回随机字母数字字符串* *@param{Integer}len所需长度*@param{String}an可选(字母数字),“a”(字母),“n”(数字)*@return{字符串}*/函数randomString(len,an){an=an&&an.toLowerCase();var str=“”,i=0,min=an==“a”?10 : 0,max=an==“n”?10 : 62;对于(;i++<len;){var r=数学随机()*(最大值-最小值)+最小值<<0;str+=String.fromCharCode(r+=r>9?r<36?55:61:48);}返回str;}console.log(randomString(10));//即:“4Z8INGag9v”console.log(randomString(10,“a”));//即:“aUkZuHNcWw”console.log(randomString(10,“n”));//即:“9055739230”
虽然以上使用了对期望的A/N、A、N输出的附加检查,让我们将其分解为基本要素(仅限字母数字),以便更好地理解:
创建一个接受参数的函数(随机字符串结果的所需长度)创建一个空字符串,如var str=“”;连接随机字符在循环内创建一个从0到61(0..9+a.Z+a..Z=62)的rand索引编号创建一个条件逻辑来调整/修复rand(因为它是0..61),将其递增一些数字(参见下面的示例),以获取正确的CharCode编号和相关字符。在循环内部连接到str一个String.fromCharCode(递增rand)
让我们想象一下ASCII字符表范围:
_____0....9______A..........Z______a..........z___________ Character
| 10 | | 26 | | 26 | Tot = 62 characters
48....57 65..........90 97..........122 CharCode ranges
Math.floor(Math.random*62)给出了从0..61(我们需要的)的范围。让我们修复随机数以获得正确的charCode范围:
| rand | charCode | (0..61)rand += fix = charCode ranges |
------+----------+----------+--------------------------------+-----------------+
0..9 | 0..9 | 48..57 | rand += 48 = 48..57 |
A..Z | 10..35 | 65..90 | rand += 55 /* 90-35 = 55 */ = 65..90 |
a..z | 36..61 | 97..122 | rand += 61 /* 122-61 = 61 */ = 97..122 |
上表中的条件运算逻辑:
rand += rand>9 ? ( rand<36 ? 55 : 61 ) : 48 ;
// rand += true ? ( true ? 55 else 61 ) else 48 ;
根据上面的解释,下面是生成的字母数字代码段:
函数randomString(len){var str=“”;//字符串结果对于(var i=0;i<len;i++){//循环“len”次数var rand=数学地板(Math.random()*62);//随机:0..61var charCode=rand+=rand>9?(兰特<36?55:61):48;//获取正确的charCodestr+=字符串.fromCharCode(charCode);//将字符添加到str}返回str;//完成所有循环后,返回连接字符串}console.log(randomString(10));//即:“7GL9F0ne6t”
或者,如果您愿意:
const randomString=(n,r=“”)=>{而(n--)r+=String.fromCharCode((r=Math.random()*62|0,r+=r>9?(r<36?55:61):48));返回r;};console.log(randomString(10))
这一个结合了许多给出的答案。
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);
我用了一个月,效果很好。