本文介绍了Javascript (node.js) 特定的随机字符串生成器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找一种有效的方法来构建具有特定要求但长度可能不同的随机字符串.它必须:
I'm looking for an efficient way to build a random string that has specific requirements but can vary in length. It must:
- 至少包含一个大写字符.
- 至少包含一个小写字符.
- 至少包含一个数字.
- 至少包含以下特殊字符之一:_-|@.,?/!~#$%^&*(){}[]+=
随机字符串不必是唯一的,但如果是,那就更好了.它将在 node.js 服务器中使用,因此可以使用任何加密库.我看到 Math.random().toString(36)
很接近但并没有让我得到一切.我不确定是否应该为此尝试构建一个正则表达式.
The random string doesn't have to be unique but if it is, its better. It will be used in a node.js server so any crypto library can be made use of. I saw Math.random().toString(36)
which comes close but doesn't get me everything. I'm not sure if I should just try to build a regex for this.
推荐答案
var randomString = (function() {
// Define character classes to pick from randomly.
var uppers = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var lowers = 'abcdefghijklmnopqrstuvwxyz';
var numbers = '0123456789';
var specials = '_-|@.,?/!~#$%^&*(){}[]+=';
var charClasses = [uppers, lowers, numbers, specials];
var minLen = charClasses.length;
function chooseRandom(x) {
var i = Math.floor(Math.random() * x.length);
return (typeof(x)==='string') ? x.substr(i,1) : x[i];
}
// Define the function to actually generate a random string.
return function(maxLen) {
maxLen = (maxLen || 36);
if (maxLen < minLen) { throw new Error('length must be >= ' + minLen); }
do { // Append a random char from a random char class.
var str='', usedClasses={}, charClass;
while (str.length < maxLen) {
charClass = chooseRandom(charClasses);
usedClasses[charClass] = true;
str += chooseRandom(charClass);
}
// Ensure we have picked from every char class.
} while (Object.keys(usedClasses).length !== charClasses.length);
return str;
}
})();
randomString(); // => "o4m3H@YC7j0r@^gsY@1vlg2]cI66|9^beZ1)"
randomString(); // => "R6-K0Kq%4O0Je*=iPbVaV|bo-_,,g[j8wTW2"
randomString(); // => "!uu5NUWs1P}SRN78l}32Gno$]2m5PV+h+wTG"
这篇关于Javascript (node.js) 特定的随机字符串生成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!