JavaScript random password with specific format - javascript

I would like to generate a random password respecting the following format:
at least one uppercase character
at least one lowercase character
at least one digit
the length should be at least 6 characters
I thought about it and the only thing I could think of is some function that is quite long and ugly. Could you guys offer me a simpler, more efficient way of doing this?
PS: I'm using this function not on the client side, but on the server side, on my Node.js web application.

Here is my solution:
/**
* sets of charachters
*/
var upper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
var lower = 'abcdefghijklmnopqrstuvwxyz'
var digit = '0123456789'
var all = upper + lower + digit
/**
* generate random integer not greater than `max`
*/
function rand (max) {
return Math.floor(Math.random() * max)
}
/**
* generate random character of the given `set`
*/
function random (set) {
return set[rand(set.length - 1)]
}
/**
* generate an array with the given `length`
* of characters of the given `set`
*/
function generate (length, set) {
var result = []
while (length--) result.push(random(set))
return result
}
/**
* shuffle an array randomly
*/
function shuffle (arr) {
var result = []
while (arr.length) {
result = result.concat(arr.splice(rand[arr.length - 1]))
}
return result
}
/**
* do the job
*/
function password (length) {
var result = [] // we need to ensure we have some characters
result = result.concat(generate(1, upper)) // 1 upper case
result = result.concat(generate(1, lower)) // 1 lower case
result = result.concat(generate(1, digit)) // 1 digit
result = result.concat(generate(length - 3, all)) // remaining - whatever
return shuffle(result).join('') // shuffle and make a string
}
console.log(password(6))

How about we place the formats into strings and we can place than into an array, then randomly chose one and randomly chose and item in that sub-array item:
var uppers = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var lowers = "abcdefghijklmnopqrstuvwxyz";
var digits = "01234567890";
var all = uppers + lowers + digits;
var choices = [uppers,lowers,digits];
var checks = [];
var password = "";
var ranLength = Math.ceil(Math.random()*10)+3;
for(var i=0; i<ranLength; i++){
var choice = choices[Math.ceil(Math.random()*3)-1];
var choiceItem = choice[Math.ceil(Math.random()*(choice.length))-1]
password += choiceItem;
}
for(var i=0; i<3; i++){ // Append needed values to end
var choice = choices[i];
var choiceItem = choice[Math.ceil(Math.random()*(choice.length))-1]
password += choiceItem;
}
password = password.split('').sort(function(){
return 0.5 - Math.random();
}).join('');
alert(password);
Edited: Sorry made a small mistake. Fixed.

Try this...
var randomstring = Math.random().toString(36).slice(-8);

Related

Split JSON every N

I'm trying to separate a json into several pieces n times depending on the size of the json and the limit of characters within a field. For example, if the json occupies 16000 characters I divide it by 4000 (which is the limit per field) and thus divide it into 4 pieces type string[0], string[1],string[2],string[3] and then print them to the screen.
I have this code but it always gives me the following error:
Error: Index and length must refer to a location within the string. Parameter name: length
var splitA = [];
function separatedFields(nCharacter, valueDeInfo) {
var limit = 4000;
var split = [];
var nfield = Math.ceil((nCharacter) / limit);
var begin = 0;
var end = 4000;
for (i = 0; i < nfield; i++) {
if (i == nfield - 1) {
split[i] = valueDeInfo.slice(begin, end);
begin = end;
end = nCharacter;
} else {
split[i] = valueDeInfo.slice(begin, end);
begin = end;
end = end + 4000;
}
}
return split;
}
splitA = separatedFields(nCharacter, valueDeInfo);
Write("ARRAY FIRST 4000: " + splitA[0]);
Example of input/output:
valueDeInfo = ['{"Status":"OK","RequestID":"e5517d4e-ee43-451a-bbe8-09f9fc714c21","Results":[{"CustomerKey":null,"Name":"Control","ObjectID":null,"FieldType":"Number","IsPrimaryKey":false,"MaxLength":0,"Ordinal":3,"DefaultValue":"1","DataExtension":null,"StorageType":"Unspecified","DataType":null,"ValueType":"xsdstring","PropertyType":"string","IsCreatable":false,"IsUpdatable":false,"IsRetrievable":false,"IsQueryable":false,"IsFilterable":false,"IsPartnerProperty":false,"IsAccountProperty":false,"PartnerMap":null,"AttributeMaps":null,"Markups":null,"Precision":0,"Scale":0,"Label":null,"Description":null,"MinLength":0,"MinValue":null,"MaxValue":null,"IsRequired":false,"IsViewable":false,"IsEditable":false,"IsNillable":false,"IsRestrictedPicklist":false,"PicklistItems":null,"IsSendTime":false,"DisplayOrder":0,"References":null,"RelationshipName":null,"Status":null,"IsContextSpecific":false,"Client":null,"PartnerKey":null,"PartnerProperties":null,"CreatedDate":"0001-01-01T00:00:00.000","ModifiedDate":null,"ID":0,"Owner":null,"CorrelationID":null,"ObjectState":null,"IsPlatformObject":false}, {"CustomerKey":null,"Name":"CategoryID","ObjectID":null,"FieldType":"Number","IsPrimaryKey":false,"MaxLength":0,"Ordinal":8,"DefaultValue":"","DataExtension":null,"StorageType":"Unspecified","DataType":null,"ValueType":"xsdstring","PropertyType":"string","IsCreatable":false,"IsUpdatable":false,"IsRetrievable":false,"IsQueryable":false,"IsFilterable":false,"IsPartnerProperty":false,"IsAccountProperty":false,"PartnerMap":null,"AttributeMaps":null,"Markups":null,"Precision":0,"Scale":0,"Label":null,"Description":null,"MinLength":0,"MinValue":null,"MaxValue":null,"IsRequired":false,"IsViewable":false,"IsEditable":false,"IsNillable":false,"IsRestrictedPicklist":false,"PicklistItems":null,"IsSendTime":false,"DisplayOrder":0,"References":null,"RelationshipName":null,"Status":null,"IsContextSpecific":false,"Client":null,"PartnerKey":null,"PartnerProperties":null,"CreatedDate":"0001-01-01T00:00:00.000","ModifiedDate":null,"ID":0,"Owner":null,"CorrelationID":null,"ObjectState":null,"IsPlatformObject":false}, {"CustomerKey":null,"Name":"IsSendable","ObjectID":null,"FieldType":"Boolean","IsPrimaryKey":false,"MaxLength":0,"Ordinal":2,"DefaultValue":"","DataExtension":null,"StorageType":"Unspecified","DataType":null,"ValueType":"xsdstring","PropertyType":"string","IsCreatable":false,"IsUpdatable":false,"IsRetrievable":false,"IsQueryable":false,"IsFilterable":false,"IsPartnerProperty":false,"IsAccountProperty":false,"PartnerMap":null,"AttributeMaps":null,"Markups":null,"Precision":0,"Scale":0,"Label":null,"Description":null,"MinLength":0,"MinValue":null,"MaxValue":null,"IsRequired":false,"IsViewable":false,"IsEditable":false,"IsNillable":false,"IsRestrictedPicklist":false,"PicklistItems":null,"IsSendTime":false,"DisplayOrder":0,"References":null,"RelationshipName":null,"Status":null,"IsContextSpecific":false,"Client":null,"PartnerKey":null,"PartnerProperties":null,"CreatedDate":"0001-01-01T00:00:00.000","ModifiedDate":null,"ID":0,"Owner":null,"CorrelationID":null,"ObjectState":null,"IsPlatformObject":false}, {"CustomerKey":null,"Name":"Name","ObjectID":null,"FieldType":"Text","IsPrimaryKey":true,"MaxLength":50,"Ordinal":0,"DefaultValue":"","DataExtension":null,"StorageType":"Unspecified","DataType":null,"ValueType":"xsdstring","PropertyType":"string","IsCreatable":false,"IsUpdatable":false,"IsRetrievable":false,"IsQueryable":false,"IsFilterable":false,"IsPartnerProperty":false,"IsAccountProperty":false,"PartnerMap":null,"AttributeMaps":null,"Markups":null,"Precision":0,"Scale":0,"Label":null,"Description":null,"MinLength":0,"MinValue":null,"MaxValue":null,"IsRequired":true,"IsViewable":false,"IsEditable":false,"IsNillable":false,"IsRestrictedPicklist":false,"PicklistItems":null,"IsSendTime":false,"DisplayOrder":0,"References":null,"RelationshipName":null,"Status":null,"IsContextSpecific":false,"Client":null,"PartnerKey":null,"PartnerProperties":null,"CreatedDate":"0001-01-01T00:00:00.000","ModifiedDate":null,"ID":0,"Owner":null,"CorrelationID":null,"ObjectState":null,"IsPlatformObject":false}, {"CustomerKey":null,"Name":"IsRequired","ObjectID":null,"FieldType":"Boolean","IsPrimaryKey":false,"MaxLength":0,"Ordinal":10,"DefaultValue":"","DataExtension":null,"StorageType":"Unspecified","DataType":null,"ValueType":"xsdstring","PropertyType":"string","IsCreatable":false,"IsUpdatable":false,"IsRetrievable":false,"IsQueryable":false,"IsFilterable":false,"IsPartnerProperty":false,"IsAccountProperty":false,"PartnerMap":null,"AttributeMaps":null,"Markups":null,"Precision":0,"Scale":0,"Label":null,"Description":null,"MinLength":0,"MinValue":null,"MaxValue":null,"IsRequired":false,"IsViewable":false,"IsEditable":false,"IsNillable":false,"IsRestrictedPicklist":false,"PicklistItems":null,"IsSendTime":false,"DisplayOrder":0,"References":null,"RelationshipName":null,"Status":null,"IsContextSpecific":false,"Client":null,"PartnerKey":null,"PartnerProperties":null,"CreatedDate":"0001-01-01T00:00:00.000","ModifiedDate":null,"ID":0,"Owner":null,"CorrelationID":null,"ObjectState":null,"IsPlatformObject":false}, {"CustomerKey":null,"Name":"infoDE3","ObjectID":null,"FieldType":"Text","IsPrimaryKey":false,"MaxLength":4000,"Ordinal":18,"DefaultValue":"","DataExtension":null,"StorageType":"Unspecified","DataType":null,"ValueType":"xsdstring","PropertyType":"string","IsCreatable":false,"IsUpdatable":false,"IsRetrievable":false,"IsQueryable":false,"IsFilterable":false,"IsPartnerProperty":false,"IsAccountProperty":false,"PartnerMap":null,"AttributeMaps":null,"Markups":null,"Precision":0,"Scale":0,"Label":null,"Description":null,"MinLength":0,"MinValue":null,"MaxValue":null,"IsRequired":true,"IsViewable":false,"IsEditable":false,"IsNillable":false,"IsRestrictedPicklist":false,"PicklistItems":null,"IsSendTime":false,"DisplayOrder":0,"References":null,"RelationshipName":null,"Status":null,"IsContextSpecific":false,"Client":null,"PartnerKey":null,"PartnerProperties":null,"CreatedDate":"0001-01-01T00:00:00.000","ModifiedDate":null,"ID":0,"Owner":null,"CorrelationID":null,"ObjectState":null,"IsPlatformObject":false}, {"CustomerKey":null,"Name":"Description","ObjectID":null,"FieldType":"Text","IsPrimaryKey":false,"MaxLength":4000,"Ordinal":6,"DefaultValue":"","DataExtension":null,"StorageType":"Unspecified","DataType":null,"ValueType":"xsdstring","PropertyType":"string","IsCreatable":false,"IsUpdatable":false,"IsRetrievable":false,"IsQueryable":false,"IsFilterable":false,"IsPartnerProperty":false,"IsAccountProperty":false,"PartnerMap":null,"AttributeMaps":null,"Markups":null,"Precision":0,"Scale":0,"Label":null,"Description":null,"MinLength":0,"MinValue":null,"MaxValue":null,"IsRequired":false,"IsViewable":false,"IsEditable":false,"IsNillable":false,"IsRestrictedPicklist":false,"PicklistItems":null,"IsSendTime":false,"DisplayOrder":0,"References":null,"RelationshipName":null,"Status":null,"IsContextSpecific":false,"Client":null,"PartnerKey":null,"PartnerProperties":null,"CreatedDate":"0001-01-01T00:00:00.000","ModifiedDate":null,"ID":0,"Owner":null,"CorrelationID":null,"ObjectState":null,"IsPlatformObject":false}, {"CustomerKey":null,"Name":"ModifiedDate","ObjectID":null,"FieldType":"Date","IsPrimaryKey":false,"MaxLength":0,"Ordinal":7,"DefaultValue":"","DataExtension":null,"StorageType":"Unspecified","DataType":null,"ValueType":"xsdstring","PropertyType":"string","IsCreatable":false,"IsUpdatable":false,"IsRetrievable":false,"IsQueryable":false,"IsFilterable":false,"IsPartnerProperty":false,"IsAccountProperty":false,"PartnerMap":null,"AttributeMaps":null,"Markups":null,"Precision":0,"Scale":0,"Label":null,"Description":null,"MinLength":0,"MinValue":null,"MaxValue":null,"IsRequired":false,"IsViewable":false,"IsEditable":false,"IsNillable":false,"IsRestrictedPicklist":false,"PicklistItems":null,"IsSendTime":false,"DisplayOrder":0,"References":null,"RelationshipName":null,"Status":null,"IsContextSpecific":false,"Client":null,"PartnerKey":null,"PartnerProperties":null,"CreatedDate":"0001-01-01T00:00:00.000","ModifiedDate":null,"ID":0,"Owner":null,"CorrelationID":null,"ObjectState":null,"IsPlatformObject":false}']
nCharacters = valueDeinfo.length;
The correct output would be:
{"Status":"OK","RequestID":"e5517d4e-ee43-451a-bbe8-09f9fc714c21","Results":[{"CustomerKey":null,"Name":"Control","ObjectID":null,"FieldType":"Number","IsPrimaryKey":false,"MaxLength":0,"Ordinal":3,"DefaultValue":"1","DataExtension":null,"StorageType":"Unspecified","DataType":null,"ValueType":"xsdstring","PropertyType":"string","IsCreatable":false,"IsUpdatable":false,"IsRetrievable":false,"IsQueryable":false,"IsFilterable":false,"IsPartnerProperty":false,"IsAccountProperty":false,"PartnerMap":null,"AttributeMaps":null,"Markups":null,"Precision":0,"Scale":0,"Label":null,"Description":null,"MinLength":0,"MinValue":null,"MaxValue":null,"IsRequired":false,"IsViewable":false,"IsEditable":false,"IsNillable":false,"IsRestrictedPicklist":false,"PicklistItems":null,"IsSendTime":false,"DisplayOrder":0,"References":null,"RelationshipName":null,"Status":null,"IsContextSpecific":false,"Client":null,"PartnerKey":null,"PartnerProperties":null,"CreatedDate":"0001-01-01T00:00:00.000","ModifiedDate":null,"ID":0,"Owner":null,"CorrelationID":null,"ObjectState":null,"IsPlatformObject":false}, {"CustomerKey":null,"Name":"CategoryID","ObjectID":null,"FieldType":"Number","IsPrimaryKey":false,"MaxLength":0,"Ordinal":8,"DefaultValue":"","DataExtension":null,"StorageType":"Unspecified","DataType":null,"ValueType":"xsdstring","PropertyType":"string","IsCreatable":false,"IsUpdatable":false,"IsRetrievable":false,"IsQueryable":false,"IsFilterable":false,"IsPartnerProperty":false,"IsAccountProperty":false,"PartnerMap":null,"AttributeMaps":null,"Markups":null,"Precision":0,"Scale":0,"Label":null,"Description":null,"MinLength":0,"MinValue":null,"MaxValue":null,"IsRequired":false,"IsViewable":false,"IsEditable":false,"IsNillable":false,"IsRestrictedPicklist":false,"PicklistItems":null,"IsSendTime":false,"DisplayOrder":0,"References":null,"RelationshipName":null,"Status":null,"IsContextSpecific":false,"Client":null,"PartnerKey":null,"PartnerProperties":null,"CreatedDate":"0001-01-01T00:00:00.000","ModifiedDate":null,"ID":0,"Owner":null,"CorrelationID":null,"ObjectState":null,"IsPlatformObject":false}, {"CustomerKey":null,"Name":"IsSendable","ObjectID":null,"FieldType":"Boolean","IsPrimaryKey":false,"MaxLength":0,"Ordinal":2,"DefaultValue":"","DataExtension":null,"StorageType":"Unspecified","DataType":null,"ValueType":"xsdstring","PropertyType":"string","IsCreatable":false,"IsUpdatable":false,"IsRetrievable":false,"IsQueryable":false,"IsFilterable":false,"IsPartnerProperty":false,"IsAccountProperty":false,"PartnerMap":null,"AttributeMaps":null,"Markups":null,"Precision":0,"Scale":0,"Label":null,"Description":null,"MinLength":0,"MinValue":null,"MaxValue":null,"IsRequired":false,"IsViewable":false,"IsEditable":false,"IsNillable":false,"IsRestrictedPicklist":false,"PicklistItems":null,"IsSendTime":false,"DisplayOrder":0,"References":null,"RelationshipName":null,"Status":null,"IsContextSpecific":false,"Client":null,"PartnerKey":null,"PartnerProperties":null,"CreatedDate":"0001-01-01T00:00:00.000","ModifiedDate":null,"ID":0,"Owner":null,"CorrelationID":null,"ObjectState":null,"IsPlatformObject":false}, {"CustomerKey":null,"Name":"Name","ObjectID":null,"FieldType":"Text","IsPrimaryKey":true,"MaxLength":50,"Ordinal":0,"DefaultValue":"","DataExtension":null,"StorageType":"Unspecified","DataType":null,"ValueType":"xsdstring","PropertyType":"string","IsCreatable":false,"IsUpdatable":false,"IsRetrievable":false,"IsQueryable":false,"IsFilterable":false,"IsPartnerProperty":false,"IsAccountProperty":false,"PartnerMap":null,"AttributeMaps":null,"Markups":null,"Precision":0,"Scale":0,"Label":null,"Description":null,"MinLength":0,"MinValue":null,"MaxValue":null,"IsRequired":true,"IsViewable":false,"IsEditable":false,"IsNillable":false,"IsRestrictedPicklist":false,"PicklistItems":null,"IsSendTime":false,"DisplayOrder":0,"References":null,"RelationshipName":null,"Status":null,"IsContextSpecific":false,"Client":null,"PartnerKey":null,"PartnerProperties":null,"CreatedDate":"0001-01-0
Basically, in splitA[0] should be the first 4000 characters, in split[1] should be in the next 4000 characters and so on until you reach nCharacters
So you basically just want to split a string at a given number of characters?
You can try a regex for that
const splitAtInterval = (string, interval) => {
const r = new RegExp(`.{1,${interval}}`, 'g')
return string.match(r);
}
var text = "Some random string (in your case your JSON string)";
console.log(splitAtInterval(text, 4));
There are other options, just search google for "split string after x characters". for example https://bobbyhadz.com/blog/javascript-split-string-substrings-n-characters
Obviously, as mentioned in the comments, those strings will not be valid json anymore. You will have to fetch all the entries again and connect them via join.

How can I replace several letters in string in javascript?

I'm building a word game. One of the functions I need is a function that receives a word and replaces several words with (_) and gives the incomplete word as output. I want the number of words to be replaced and the location of those words to be chosen randomly. The code I wrote, although it uses for, is only able to replace one word. What changes should I make in the for part of the code that has the ability to move several words?
for example : "laptop" => "l_pt_p"
function wordToIncomplete(word) {
let randomNumber = Math.floor(Math.random() * 3) + 1
let _randomNumber = Math.floor(Math.random() * word.length)
let _word = "";
for (let index = 0; index < randomNumber; index++) {
_word = word.replace(word[_randomNumber], '_');
}
return _word
}
Yes, as #Barmar mentioned, naming is important.
What changes should I make in the for part of the code that has the ability to move several words
The problem here is that _randomNumber is always same during the loop.
function wordToIncomplete(word) {
const randomNumberOfCharactersToBeReplaced =
Math.floor(Math.random() * word.length) + 1;
let result = word;
for (let i = 0; i < randomNumberOfCharactersToBeReplaced; i++) {
// suppose we don't care about whether the character is already replaced or not.
const randomIndexToBeReplaced = Math.floor(Math.random() * word.length);
result[randomIndexToBeReplaced] = "_";
}
return result;
}
I think your problem is you did not put your _randomNumber in the loop to re-generate your removed character index
function wordToIncomplete(word) {
let randomNumber = Math.floor(Math.random() * 3) + 1
let _word = word;
for (let index = 0; index < randomNumber; index++) {
let _randomNumber = Math.floor(Math.random() * _word.length)
_word = _word.replace(_word[_randomNumber], '_');
}
return _word
}
const testingWords = "testing words"
console.log(wordToIncomplete(testingWords))
But with this solution, I think it will encounter another problem that it may check the same character which is already replaced earlier
Therefore, I modified your code a bit with while loop
function wordToIncomplete(word) {
let randomNumber = Math.floor(Math.random() * 3) + 1
let _word = word;
let index = 0;
while (index < randomNumber) {
let _randomNumber = Math.floor(Math.random() * _word.length)
if (_word[_randomNumber] === '_') { // we don't need to replace the checked words
continue;
}
_word = _word.replace(_word[_randomNumber], '_');
index++;
}
return _word
}
const testingWords = "testing words"
console.log(wordToIncomplete(testingWords))
By the way, you also did not assign value for _word, so I changed it to
let _word = word
The example returns an array of letters which is easier to work with, but if for some reason you want a string, do the following to the last line:
return chars.join('');
Note: this example actually adjusts dynamically the number of letters to be replaced which is from 30% to 60% of word.length.
Details are commented in example below
// Utility function
const log = data => console.log(JSON.stringify(data));
// Random integer range function
const randRng = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
const fragWord = word => {
/*
The result of the following expressions is a random number that's
within the range of 30% to 60% of total length of >word<
>word< string is converted into an array of letters called >chars<
*/
const size = word.length;
const lo = Math.ceil(0.3 * size);
const hi = Math.ceil(0.6 * size);
let qty = randRng(lo, hi);
let chars = word.split('');
/*
At each iteration of >chars< a random index number is generated.
If there's a '_' at that index, the current iteration is skipped
and qty increases by 1 to compensate.
Otherwise the letter at that index is replaced with a '_'
*/
skip:
for (let i = 0; i < qty; i++) {
let index = randRng(0, size - 1);
let char = chars.at(index);
if (char === '_') {
qty = qty + 1;
continue skip;
}
chars[index] = '_';
}
return chars;
};
log(fragWord('fragment'));
log(fragWord('appearance'));
log(fragWord('institutionalization'));
log(fragWord('institutionalization'));
Here is my take on it:
function shfl(array) { // Durstenfeld shuffle, based on Fisher-Yates
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i],array[j]]=[array[j],array[i]];
}
return array;
}
function getWd(word) {
const n=~~(Math.random()*3)+1, // 1...3
wa=word.split(""), // word as char-array
pos=shfl(wa.map((_,i)=>i))
.slice(0,n); // 1...3 character positions to be replaced by _
pos.forEach(p=>wa[p]="_")
return wa.join("");
}
console.log(
"And here comes my supercalifragilisticexpialidocious word I want to process".split(" ")
.map(getWd).join(" ")
);
I use the Durstenfeld shuffle to pick out random character positions of each word.
In getWd() I split the word into an array wa. This array is then the base for finding 1..3 positions (pos) to be replaced by _. After replacing the positions I join("") the characters in wa again and return them as the changed word.
Another expression I'd like to explain is
~~(Math.random()*3)+1
The ~ operator ("bitwise negation") will implicitly convert any number into an integer (similar to Math.floor()). By applying it twice (~~) the actual bitwise negation will be reversed and the result is thus a shorthand for Math.floor().

Generate string of random number that includes some number and exclude some number

I have a problem about generating string in javascript.
I have an array of number that string should contains atleast 1, and 1 number(up to 7 digits) that must not contains in a string. String length must be 7.
var incNumber = ["15","51","14","41","55","39","23"];
var exclude = ... //input from user
I tried to generate it by random select from array, random position and random other number around selected number. Then check if string contains excluded number, generate it again.
//random select number
var getRandom = incNumber[Math.floor(Math.random() * incNumber.length)];
//random position of number
var position = Math.floor(Math.random() * 6);
//length of other string after selected number
var afterlen = 7 - (position+2);
//genNum(...) is my function that use to generate string of number in specific length.
var nstr = genNum(position)+getRandom+genNum(afterlen);
while (nstr.includes(exclude)) {
nstr = genNum(position)+getRandom+genNum(afterlen);
}
but doing this take too long time or sometimes freeze my browser. How should I fix it.?
edited: It's my homework about phonenumber.
final string should be like "37915002"
Edited my code again
Does that now match your needs? It has got pretty messy and I'm not sure if it's correct (I'm never sure.. xD) hope you can get some inspiration though.
// Variables
var initialList = ["100", "5", "19", "88", "10", "90"];
var excludeList = ["9", "10"];
var resultLength = 7;
var finalString = "";
// Create a third final array that is filtered
var finalList = initialList.filter(element => {
let shouldBeIncluded = true;
excludeList.forEach(excluder => {
Array.from(excluder).forEach(excluderFragment => {
if (element.includes(excluderFragment)) shouldBeIncluded = false;
});
});
if (shouldBeIncluded) return true;
});
// Check if all were excluded
if (finalList.length == 0) {
// Do error handling here
} else {
// Create the list
for (let i = 0; i < resultLength; i++) {
finalString += finalList[Math.floor(Math.random() * finalList.length)];
}
// Shorten the list because multiple digits values
finalString = finalString.slice(0, 7);
console.log(finalString);
}
You could start by filtering the unwanted number from the incNumber and doing everything the same way but on the new array
var incNumber = ["15","51","14","41","55","39","23"];
var exclude = "12";
var filteredNumbber =incNumber.filter(number=> number!==exclude);
var random = filteredNumbber[Math.floor(Math.random() * filteredNumbber.length)];
if we assume exclude is not a value but instead an array of values you would change the formula to
var incNumber = ["15","51","14","41","55","39","23"];
var exclude = ["15"];
var filteredNumbber =incNumber.filter(number=> !exclude.includes(number));
var random = filteredNumbber[Math.floor(Math.random() * filteredNumbber.length)];
as some people suggested random variable may end up as undefined if we exclude all the numbers inside of incNumber, if that was the case we should add an additional check in case that happens
if (random!==undefined) var nstr = genNum(position)+random+genNum(afterlen);

Generate random string with capital letters and numbers without O and 0

I'm wanting to generate a random string with a length of 12 with capital letters only and numbers with no letter O or the number 0 in javascript. here is what I have:
Math.random().toString(36).substr(2, 12)
but the problem is that it is not all capital and i don't want the letter O or the number 0. thanks
function rand_str_without_O0() {
const list = "ABCDEFGHIJKLMNPQRSTUVWXYZ123456789";
var res = "";
for(var i = 0; i < 12; i++) {
var rnd = Math.floor(Math.random() * list.length);
res = res + list.charAt(rnd);
}
return res;
}
Usage:
var randomString = rand_str_without_O0();
let foo = function(length) { //length should be <= 7
return Math.random().toString(36).toUpperCase().replace(/[0-9O]/g, '').substring(1,length+1)
}
response = foo(6) + foo(6)
This will first generate random string convert to uppercase, then remove the un-needed values and then create substring of required length. As far as I have seen, this will generate a string of at-least 7 characters so you can use it twice to generate string of length 12.
This is a quick solution and probably not optimal.
var myString = function(len, excluded) {
var included = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
// remove the excluded chars from the included string
for (var i = 0; i < excluded.length; i++) {
included = included.split(excluded[i]).join('');
}
// add len random chars form whatever is left.
var output = '';
for (var i = 0; i < len; i++) {
output += included.charAt(Math.random() * included.length);
}
return output;
}
And you call it with the desired length and an array of characters to exclude:
console.log(myString(12, ['0', 'O']));
EDIT: This solution allows the output length and the chars to be excluded to be passed on as parameters.
var all_chars_without_O0 = 'ABCDEFGHIJKLMNPQRSTUVWXYZ123456789'.split('');
// Returns a random integer between min (included) and max (excluded)
// Using Math.round() will give you a non-uniform distribution!
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
function pickRandom(arr) {
return arr[getRandomInt(0, arr.length)];
}
function randomString(length = 12, chars = all_chars_without_O0) {
var s = '';
while (length--)
s += pickRandom(chars);
return s;
}
https://jsfiddle.net/MrQubo/fusb1746/1/
Or using lodash:
var all_chars_without_O0 = 'ABCDEFGHIJKLMNPQRSTUVWXYZ123456789'.split('');
function randomString(length = 12, chars = all_chars_without_O0) {
return _.sampleSize(chars, length).join('');
}
However, you should be warned, that Math.random() doesn't provide cryptographically secure random numbers. See Math.random() for more information.

Javascript - generating a random number of specified length from set of specified values

I wanted to generate a random number 32 characters in length from a specified set of characters.
For example:
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZ";
var string_length = 32;
Which would then return a random number of length 32 using the specified characters.
Something like this?
Check out the jsfiddle. I modified it so you can see the progression as the result grows: http://jsfiddle.net/YuyNL/
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZ"; // Pool of potential characters
var string_length = 32; // Desired length of result
var num_chars = chars.length; // Total number of characters in pool
var result = ''; // Container to store result
while(string_length--) { // Run a loop for a duration equal to the length of the result
// For each iteration, get a random number from 0 to the size of the
// number of characters you're using, use that number to grab the index
// of the character stored in 'chars', and add it to the end of the result
result += chars[ Math.floor( Math.random() * num_chars ) ];
}
$('body').append(result + '<br>'); // This just appends the result to the 'body'
// if you're using jQuery
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZ";
var string_length = 32;
var myrnd = [], pos;
// loop as long as string_length is > 0
while (string_length--) {
// get a random number between 0 and chars.length - see e.g. http://www.shawnolson.net/a/789/make-javascript-mathrandom-useful.html
pos = Math.floor(Math.random() * chars.length);
// add the character from the base string to the array
myrnd.push(chars.substr(pos, 1));
}
// join the array using '' as the separator, which gives us back a string
myrnd.join(''); // e.g "6DMIG9SP1KDEFB4JK5KWMNSI3UMQSSNT"
// Set up a return variable
var randStr = "";
// Split the chars into individual array elements
chars = chars.split("");
// Until string_length is 0...
while (string_length--)
// ... select a random character from the array
randStr += chars[Math.floor(Math.random() * chars.length)];
// return the string
return randStr;
Here is a simple solution that should be quite easy to understand.
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZ";
var string_length = 32;
var result = "";
for(var i=0; i<string_length; i++){
var randomPos = Math.floor( Math.random() * chars.length );
result += chars.substr(randomPos, 1);
}
Maybe make it a little more flexible.
You may want the return to be an array,
if you are going to do any big integer math on it
function charsRandom(len, chars){
chars= chars || "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
len= len || 32;
var cr= [], L= chars.length;
while(len--) cr[cr.length]= chars.charAt(Math.floor(Math.random()*L));
return cr.join(''); // or return the array cr
}
alert(charsRandom())

Categories

Resources