我想要一个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”更改为其他字符。
其他回答
以下代码将使用npm包加密随机字符串生成大小为[a-zA-Z0-9]的加密安全随机字符串。使用以下方法安装:
npm install crypto-random-string
要在集合[a-zA-Z0-9]中获得30个字符的随机字符串:
const cryptoRandomString = require('crypto-random-string');
cryptoRandomString({length: 100, type: 'base64'}).replace(/[/+=]/g,'').substr(-30);
摘要:我们正在替换一个大的随机base64字符串中的/,+,=,并获取最后N个字符。
PS:在子字符串中使用-N
随机unicode字符串
此方法将返回一个随机字符串,其中包含任何受支持的unicode字符,这不是OP要求的100%,而是我想要的:
function randomUnicodeString(length){
return Array.from({length: length}, ()=>{
return String.fromCharCode(Math.floor(Math.random() * (65536)))
}).join('')
}
根本原因
这是谷歌搜索“随机字符串javascript”时的最高结果,但OP只要求a-zA-Z0-9。
最紧凑的解决方案,因为切片比子字符串短。从字符串末尾减去允许避免由随机函数生成的浮点符号:
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));
以下是CoffeeScript中的示例:
String::add_Random_Letters = (size )->
charSet = 'abcdefghijklmnopqrstuvwxyz'
@ + (charSet[Math.floor(Math.random() * charSet.length)] for i in [1..size]).join('')
可以使用
value = "abc_"
value_with_exta_5_random_letters = value.add_Random_Letters(5)
对于包含大小写字母和数字(0-9a-zA-Z)的字符串,这可能是缩小效果最好的版本:
function makeId(length) {
var id = '';
var rdm62;
while (length--) {
// Generate random integer between 0 and 61, 0|x works for Math.floor(x) in this case
rdm62 = 0 | Math.random() * 62;
// Map to ascii codes: 0-9 to 48-57 (0-9), 10-35 to 65-90 (A-Z), 36-61 to 97-122 (a-z)
id += String.fromCharCode(rdm62 + (rdm62 < 10 ? 48 : rdm62 < 36 ? 55 : 61))
}
return id;
}
此函数的内容缩小到97个字节,而顶部答案需要149个字节(因为字符列表)。