JavaScript Password Generator - multiple random values from array - javascript

I am a newcomer to JavaScript, and have been battling with this relatively simple program for a few days now.
The program: I have a website with a button on. When you click the button, a password is generated (from an array) and displayed for the user.
The problem: "function generate()" displays the single same generated character 10 times, instead of 10 different characters 10 times, which naturally would make a much stronger password. I want it to randomize 10 different characters into a password, not the same character 10 times. So the program works, but not as I intended.
I have created a JSfiddle containing comments for display. Note that document.write is disabled in JSfiddle, so the result is set to show in console.
https://jsfiddle.net/ohstmbym/
<!DOCTYPE html>
<html>
<head>
<title></title>
<button onclick="generate()">Button</button>
</head>
<body>
<script>
var arr = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];
randomLetter = arr[Math.floor(arr.length * Math.random())];
function generate () {for (i = 0; i < 10; i++) {document.write(randomLetter); } }
</script>
</body>
</html>
Important: I would like to understand what is wrong with the code/how to fix it - I am not just looking for somebody to solve it for me with no explanation. If you want to help me solve the problem, I am very thankful, but please explain what you do. And also, please don't rewrite the code completely like in rewriting the entire program to make it work; I am looking for solutions/explanations, not somebody write the whole thing up. If it's completely wrong and need to be entirely rewritten, please simply explain in words what should've been done instead.
Still, thank you very much in advance, I appreciate any help.
(P.S. I know only lower case letters for password generation will be of weaker security, but this is only for experimentation)

The problem is that you're not regenerating the random element, you're caching a random element once in randomLetter so it's always the same. The value of the variable will not change every time you refer to it. Put it inside the for loop to regenerate the number every iteration:
var arr = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];
function generate () {
for (i = 0; i < 10; i++) {
var randomLetter = arr[Math.floor(arr.length * Math.random())];
document.write(randomLetter);
}
}

Related

What am I missing? Lambda Challenge

I'm trying to do the Lambda challenge and the output is what its asking but its still not correct?
The problem is:
"Modify the function to transform the given string into an array where each character in the array is in the same index as it was in the string, and return it."
function convertStringToArray(s) {
var output = Array.from("hello");
return output;
}
/* Do not modify code below this line */
const exampleString = 'hello';
const stringAsArray = convertStringToArray(exampleString);
console.log(stringAsArray, '<-- should be ["h", "e", "l", "l", "o"]');
Output
["h", "e", "l", "l", "o"] <-- should be ["h", "e", "l", "l", "o"]
I did exactly what it wanted so why am I stuck?
Your code takes an argument of s - which it ignores.
I highly suspect that the lambda challenge is passing different values to your function (only using "hello" as an example) and your code is failing because it only ever returns ["h", "e", "l", "l", "o"] even when s is "world".
Try using s instead of "hello" on the first line of your function.

Picking a random index from an array is always returning me the same index?

var letters = ["a", "b", "c", "d", "e", "f", "g", "h"]
var letter = letter[Math.round(Math.random()*(quotes.length))]
Every time it just returns the last letter, g, not a random one from the array.
What am I doing wrong?
(quotes.length)
What is quotes? You want letters.
You're doing var letter = letter, but letter hasn't been defined yet. Also, when choosing a random element from an array, use Math.floor instead of Math.round:
const letters = ["a", "b", "c", "d", "e", "f", "g", "h"];
const letter = letters[Math.floor(Math.random()*letters.length)];
console.log(letter);
Probably need to fix a few typos in your code:
var letters = ["a", "b", "c", "d", "e", "f", "g", "h"]
var letter = letters[Math.round(Math.random()*(letters.length))]
Also, you may not want to use Math.round since it can cause an out-of-bound array access error. You should try Math.floor instead.
Fix the typos and you should be fine
var letter = letters[Math.round(Math.random()*(letters.length))]

split all character using javascript except '\t','\b','\n'

var str = "\tToday we are going to\b a farm to pick\r" i want to";
str.split('');
var str = "\tToday we are going to\b a farm to pick\r";
var result = str.split('');
console.log(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="result"></div>
But in result '\t', '\r','\b' replacing by symbol, like for '\t' its taking big space.
Help to get as array like
[ "\t", "T", "o", "d", "a", "y", " ", "w", "e", " ", "a", "r", "e", " ", "g", "o", "i", "n", "g", " ", "t", "o", "\b", " ", "a", " ", "f", "a", "r", "m", " ", "t", "o", " ", "p", "i", "c", "k", "\r"]
Thanks
But in result '\t', '\r','\b' replacing by symbol, like for '\t' its taking big space
If you're outputting this to a terminal console, that's just because \t is a tab, and the console output is outputting a tab, which the terminal is interpreting as a number of spaces. Similar (but different, and possibly more surprising) things will happen with \r and \b.
Help to get as array like...
That's what you're getting, it's just that when you output to the console, the output is interpreted by the terminal.
If you want to see actual backslashes, you could run the entries through JSON.stringify, but I suspect you don't. I think you probably want the array you already have.

in javascript checking items in a string variable against an English dictionary

I have the function below that selects randomly letters from an array of all English letters (plus space, plus <br/>) and stores them in a string variable.
The function has a loop that generates 2,500 random characters. I would like to check which of the sequences of letters between two spaces (i.e. " " or a space and a return (" " or <br/>) or two <br/> constitute legitimate English words.
How do I do this? In particular,
do I need to download an English dictionary
how do I compare all of my strings of characters against it
retain the words that are legitimate? Here is the code of the
function.
JS
function statement() {
var letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", " ", "<br/>"];
for (var i = 0; i <= 2500; i++) {
var random_letter = Math.floor(Math.random() * letters.length);
result += letters[random_letter];
}
document.getElementById("random1").innerHTML += result;
}
At first: you need a wordlist. If you work with a Unix OS you most probably have a medium sized wordlist in /usr/share/dict/words but you'll find many on the net, one short search gave http://www-01.sil.org/linguistics/wordlists/english/wordlist/wordsEn.txt with about 100k words. These are already sorted so you can just put them in an Array word by word. Because it is sorted you can search it with a fast binary search.
You look for words between spaces and linebreaks but it is a bit ambiguous if e.g. word<br/>word2 word3<br/> counts as word, word2, word3 or word, word2 word3 so word2 word3 would be a kind of sentence? I assume the first variation: single words, no sentences from now on for simplicity.
In the loop that produces the string, I would check every single generated character if it is space/linebreak, take the string generated so far and check that against the dictionary.
If you insist to work on the final generated string only you have to split it into single words, maybe with a regex because it is simple here:
var s = ("word1 word2<br/> <br/><br/> word3 <br/>").replace(/<br[/]>/g,"").split(/[\s]+/);
s.join(",");
//word1,word2,word3,
// the ^ last one is empty
Then loop over the array and check every word you found against the dictionary. Because the last entry in my poor version of splitting is empty and others might be empty, too (if you played around with it), you need to check every one if it is has something in it.
Instead of doing the dictionary search with a simple array and a binary search you can leave that hassle to the JavaScript engine by (ab)using an {key:value} object. (this example is sorted because of C&P from an already sorted wordlist, it does not needed to be sorted)
dict = {Banach:0,Bancroft:0,Bandung:0,"Banga lore":0,Bangkok:0,Bangladesh:0,
Bangladeshi:0,Bangor:0,Bangui:0,Banjarmasin:0,Banjul:0,Banks:0,
Banneker:0,Deleon:0,Delgado:0,Delhi:0,Delia:0,Delibes:0,Delicious:0,
Delilah:0,Delius:0,Dell:0,Dell:0,Della:0,Delmar:0,Delmarva:0,Delmer:0,
Delmonico:0,Delores:0,Deloris:0,Hanukkahs:0,Hapsburg:0,Harare:0,
Harbin:0,Hardin:0,Harding:0,Hardy:0,Hargreaves:0,Harlan:0,Harlem:0,
Harlequin:0,Harley:0,Harlow:0,Harmon:0};
dict.hasOwnProperty("Delores"); // true
dict.hasOwnProperty("foo"); // false
You use the key as the value here. The actual value is wasted in this case but you can use them for further refinement, e.g.: mark nouns, verbs, adjectives, etc. You are not restricted to numbers, of course, you can use everything, even the complete dictionary entry of that word (with pictures and music even, but that is another story).
this is working code implemented with node js
1) Yes, you do have to download the words, I get them from a url using the request module.
You basically have to turn the list of words from that website into an array by splitting it with a regualr expression, and also split your random generated strings with another regex. Then, you do a for loop to go through each of them, one at a time, comparing each real word to each generated word. Like this:
var request = require("request");
request("http://www.math.sjsu.edu/~foster/dictionary.txt", function(err,status, resp){
var letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", " ", "<br/>"];
letters = letters.map(function(letter){ return letter.toLowerCase()});
//console.log(wordsArr);
var result = "";
var c = 0;
for (var i = 0; i <= 10000; i++) {
var random_letter = Math.floor(Math.random() * letters.length);
result += letters[random_letter];
c++;
}
if(c >= 2500){
var randomResultArr = result.split(/<br\/>|<br\/><br\/>|\s/);
console.log(randomResultArr);
var matchesArr = getWordMatches(wordsArr = resp.split("\n"), result.split(/<br\/>|<br\/><br\/>|\s/));
console.log("MATCHES: " + matchesArr);
}
});
function getWordMatches(wordsArr, resultArr){
var matchesArr = [];
console.log("WORDSARR ", wordsArr.length);
console.log("RES ARR ", resultArr.length);
for(var i = 0; i < wordsArr.length; i++ ){
for(var x = 0; x < resultArr.length; x++){
if( (wordsArr[i] === resultArr[x]) && wordsArr[i] !== "" ){
matchesArr.push(wordsArr[i]);
console.log("WORD MATCH : " + wordsArr[i]);
}
}
}
return matchesArr;
}
here is a sample output of it, I had to up the 2500 to 10000 to get more matches:
WORDSARR 349901
RES ARR 747
WORD MATCH : giros
WORD MATCH : goad
WORD MATCH : kaqa
WORD MATCH : lome
WORD MATCH : mibs
MATCHES: giros,goad,kaqa,lome,mibs

how to use uppercase method with do not allowed turkish character?

I have the following code:
<input type="text" style="text-transform: uppercase" />
The string gets transformed to uppercase, but ü for example, will transform to Ü.
I want ü to transform to U, e.g. Gülay should become GULAY.
Does anyone have any idea how can I do this?
If this data is comming from a database, I suggest you treat this on your server before you send to your view.
But you can also use a javascript for that if you don't want this to happen on the server.
Check out this answer: Remove accents/diacritics in a string in JavaScript
You could use something like:
var finalString = removeDiacritics(initialString).toUpperCase();
String.prototype.turkishToLower = function () {
var string = this;
var letters = {
İ: "i", I: "i", ı: "i", Ş: "s", ş: "s", Ğ: "g", ğ: "g", Ü: "u", ü: "u", Ö: "o", ö: "o", Ç: "c", ç: "c",
};
string = string.replace(/(([İIıŞşĞğÜüÇçÖö]))/g, function (letter) {
return letters[letter];
});
return string.toLowerCase();}
String.prototype.turkishToUpper = function(){
var string = this;
var letters = { "i": "I", "ş": "S", "ğ": "G", "ü": "U", "ö": "O", "ç": "C", "ı": "I" };
string = string.replace(/(([iışğüçö]))/g, function(letter){ return letters[letter]; });
return string.toUpperCase();}
use it "string".turkishToLower()

Categories

Resources