Javascript (node.js) Specific Random String Builder
I'm looking for an efficient way to build a random string that has specific requirements but can vary in length. It must: Contain at least one uppercase character. Contain at leas
Solution 1:
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;
functionchooseRandom(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.returnfunction(maxLen) {
maxLen = (maxLen || 36);
if (maxLen < minLen) { thrownewError('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"
Solution 2:
Regex are used to check, capture, split or replace something in a string, you can't build something from zero with them.
However you can make some replacement in a string that contain a random generated number to have that you want.
Post a Comment for "Javascript (node.js) Specific Random String Builder"