nodejs提供的Math.random() 用于生成随机数字,但是并未提供生成字符串的函数,要自己写生成随机字符串逻辑比较麻烦。string-random库专门用于快速生成随机字符串,并且可以根据需求制定字符串长度以及包含的字符。下面进行相关用户的简单介绍。
1.简述
1)random(length, options) 函数的第一个参数length为要生成的字符串长度,第二个参数是选项:
- options 为true,生成包含字母、数字和特殊字符的字符串
- options 为字符串,从options字符串中提供的字符生成随机结果
- options 为对象
2)options 对象:
- options.letters
- true (默认) 允许大小写字母
- false 不允许大小写字母
- string 从提供的字符生成随机结果
3)options.numbers
- true (默认) 允许数字
- false 不允许数字
- string 从提供的字符生成随机结果
4)options.specials
- true 允许特殊字符
- false (默认) 不允许特殊字符
- string 从提供的字符生成随机结果
2. 用法demo:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| const stringRandom = require('string-random'); // 默认生成长度为8的字符串,包含大小写字母和数字的随机字符串 console.log(stringRandom()); // oSjAbc02
// 指定生成长度为16,包含大小写字母和数字的随机字符串 console.log(stringRandom(16)); // d9oq0A3vooaDod8X
// 指定生成长度为16,仅包含指定字符的字符串 console.log(stringRandom(16, '01')); // 1001001001100101
// 指定生成长度为16,包含大小写字母的随机字符串(不包含数字) console.log(stringRandom(16, { numbers: false })); // AgfPTKheCgMvwNqX
// 指定生成长度为16,包含大小写字母的随机字符串(包含数字) 同console.log(stringRandom(16)); console.log(stringRandom(16, { numbers: true })); // r48ZGVa7FsioSbse
// 包含数字的随机字符串(不包含字母) 默认是 true console.log(stringRandom(16, { letters: false })); // 0889014544916637
// 包含制定字母和数字的随机字符串 console.log(stringRandom(16, { letters: 'ABCDEFG' })); // 055B1627E43GA7D8
// 包含特殊字符 默认是false console.log(stringRandom(16, { specials: true })); // ,o=8l{iay>AOegW[ console.log(stringRandom(16, true)); // SMm,EjETKMldIM/J //包含指定特殊字符 console.log(stringRandom(16, { specials: "-" }));
|
@南非波波 github:https://github.com/swht