string random characters in a for loop - javascript

Im having trouble with the following code while trying to make a random password generator. The first two lines seem to be working as intended. I confirmed this with the following:
If I replace the "passwordText = passwordText.concat(character:" with "console.log(character)" it works in the console. Picks a random char from an array and will console log it the desired amount of times.
However, on line 3 I'm trying to concat these random chars into one string. Any ideas? I'm getting a TypeError: Cannot read property 'concat'. All variables are declared.
for (var i = 0; i < inputLength; i++) {
character = finalCriteria[Math.floor(Math.random() * finalCriteria.length)];
passwordText = passwordText.concat(character);
}
passwordText = passwordText.concat(character);
I would appreciate any guidance on this. Many thanks, Steven.
PS. This is my first week with JS, go easy on me! :)

strings don't have a concat method unlike arrays. What you need is +=:
passwordText += character;
Edit: concat not push

Thanks everyone for your help. Below worked. I also give password text a value as mentioned by caTS.
// function to return the password
function generatePassword() {
for (var i = 0; i < charLength; i++) {
passwordText += finalCriteria[Math.floor(Math.random() * finalCriteria.length)];
} return passwordText
}

Related

Generate random 6 characters based on input

Generate random 6 characters based on input. Like I want to turn 1028797107357892628 into j4w8p. Or 102879708974181177 into lg36k but I want it to be consistant. Like whenever I feed 1028797107357892628 in, it should always spit out j4w8p. Is this possible? (Without a database if possible.) I know how to generate random 6 characters but I dont know how to connect it with an input tbh. I would appreciate any help, thanks.
let rid = (Math.random() + 1).toString(36).substring(7);
You can create a custom hashing function a simple function to your code would be
const seed = "1028797089741811773";
function customHash(str, outLen){
//The 4 in the next regex needs to be the length of the seed divided by the desired hash lenght
const regx = new RegExp(`.{1,${Math.floor(str.length / outLen)}}`, 'g')
const splitted = str.match(regx);
let out = "";
for(const c of splitted){
let ASCII = c % 126;
if( ASCII < 33) ASCII = 33
out += String.fromCharCode(ASCII)
}
return out.slice(0, outLen)
}
const output = customHash(seed, 6)
console.log(output)
It is called hashing, hashing is not random. In your example to get rid:
let rid = (Math.random() + 1).toString(36).substring(7);
Because it is random, it's impossible to be able to produce "consistant result" as you expect.
You need algorithm to produce a "random" consistant result.
Thanks everyone, solved my issue.
Code:
let seed = Number(1028797089741811773)
let rid = seed.toString(36).substring(0,6)
console.log(rid)
Or:
let seed = Number(1028797089741811773)
let rid = seed.toString(36).substring(6)
console.log(rid)

easy way to multiply a value to successive substrings in javascript

Good morning, sorry for my poor English.
I'm a neophyte and I'm trying to create a javascript program that, given a string in input, if it finds inside defined substrings it returns a value to each substring and returns the sum of the values ​​found as output. Everything ok here. But I'm finding it difficult to manage the case where in front of the substring that I'm looking for, there's for example "2x" which means that the value of the next substring (or of all subsequent substring) is to be multiplied for 2. How can I write in simple code this exception?
Example:
A1 = 1
M1 = 1
input description = A1-M1
output = 2
input descritpion = 2 x A1-M1
output = 4
Thanks in advance
For more comprehesion, you can find my code below:
let str_description = "2 x A1-M1";
var time_mont = [];
var time_cloa = [];
if(str_description.includes("A1")){
time_mont.push (0.62);
} else {
time_mont.push (0);
}
if(str_description.includes("M1")){
time_mont.push (0.6);
} else {
time_mont.push (0);
}
How can I manage "2 x " subtring?

Making secret language useing charAt

I need to make a textbox with in there a word when i click on a button that word needs to convert into numbers useing charAt and that number needs to get +2 and than converted back into words and that word needs to get alerted i dont know what to do i find this really hard i made a function that is useless but i just want to show you what i did please help :)
function codeer(){
var woord2 = document.getElementById("woord")
var woordterug = woord2.charAt(0)
var woord234 = document.getElementById("woord");
var woord23 = woord234.charAt(str.length+2);
}
You could get the char code with String#charCodeAt from the character add two and build a new string with String.fromCharCode.
function codeer() {
var woord = document.getElementById("woord").value,
coded = '',
i;
for (i = 0; i < woord.length; i++) {
coded += String.fromCharCode(woord.charCodeAt(i) + 2);
}
console.log(coded);
}
<input id="woord" /> <button onclick="codeer()">cooder</button>
You should search the internet for a JavaScript rot13 example. In that code, you just need to replace the 13 with a 2, and it should work.

Javascript: How to compare to sentences word to word

I'm sort of creating typing tutor with custom options.
Not a professional (don't get mad at me for being wrong-person-wrong place) but thanks to helpful forums like stackoverflow.com and contributing traffic/people I'm able to pull it out in a day or two.
Directly now, here!
while (i < len+1){
if(boxarray[i] == orgarray[i]){
++i;
actualScore = i - 1;
}
I've searched already, '==' operator is of no use, I will not go for JSON.encode. I met similar solution at this page . But in my case I've to loop through each word while comparing two sentences. Detail is trivial, if someone please help me solve above, I won't return with complain on the same project, promise.
Okay I'm putting more code if it can help you help me.
var paratext = document.getElementById('typethis').innerHTML;
var orgstr = "start typing, in : BtXr the yellow box but. please don't shit." ;
var boxtext = document.getElementById('usit').value;
var endtrim = boxtext;
var actualScore;
var orgarray = listToArray(orgstr," ");
var boxarray = listToArray(boxtext," ");
var len = boxarray.length;
var i = 0;
var actualScore; //note var undefined that's one mistake I was making [edit]
if(orgstr.indexOf(boxtext) !== -1){
while (i < len+1){
if(boxarray[i] == orgarray[i]){
++i;
actualScore = i - 1;
}
}
alert(actualScore);
}
If I follow what you're after how about something like this:
http://jsfiddle.net/w6R9U/
var s1 = 'The dog sleeps';
var s2 = 'the dog jogs';
var s1Parts= s1.split(' ');
var s2Parts= s2.split(' ');
var score = 0;
for(var i = 0; i<s1Parts.length; i++)
{
if(s1Parts[i] === s2Parts[i])
score++;
}
"The dog sleeps" and "the dog sleeps" results in a score of 2 because of case (which could be ignored, if needed). The example above results in a score of 1. Could get a percent by using the length of the sentences. Hope this helps! If nothing else might get you started.
The following will compare each individual character, decreasing the "actualScore" for each inequality:
http://jsfiddle.net/ckKDR/
var sentence1 = "This is the original sentence.", // original text
sentence2 = "This is teh originel sentence.", // what the user typed
length = sentence1.length,
actualScore = length, // start with full points
i = 0;
while(i<length){
if(sentence1[i]!==sentence2[i]){
actualScore--; // subtract 1 from actual score
}
i++; // move to the next index
}
alert("'sentence2' is "+Math.round(100*(actualScore/length))+"% accurate");
Let's say the input is your two sentences as strings.
Then the first thing to do is to create two temporary strings, with all the non-word characters eliminated (e.g. punctuation characters). Split the sentences into string arrays by word delimiters.
Then you can assign an integer variable to score. Create an outer loop and an inner loop for the two sentences. When the words match in the sentences, increment the variable by 1, remove the word from the 2nd sentence (replace the word with a non-word character) and break out of the inner loop.
Also, use this operator for word comparison instead:
===
Your problem is
if (boxarray[i] = orgarray[i])
The single = is the assignment operator. Replace it with
===
to be a comparison.
You are not comparing you are assigning
if(boxarray[i] = orgarray[i]){
^^^
So it will be true on each iteration. Fix the typo to actually perform the check you want
if(boxarray[i] === orgarray[i]){
^^^
And how you are calculating the score looks to be wrong. You should be doing something like
var score = orgstr.length;
while...
if(boxarray[i] === orgarray[i]){
score--;
}
{
string1="string1";
string2="string2 is here";
changepercent(string1,string2);
}
function changepercent(string1,string2) {
var s1Parts= string1.split(' ');
var s2Parts= string2.split(' ');
var matched = 0;
for(var i = 0; i<s1Parts.length; i++)
{
for(var j = 0; j<s2Parts.length; j++)
{
if(s1Parts[i] === s2Parts[j])
matched++;
}
}
var percentage=(matched/Math.max(s1Parts.length, s2Parts.length))*100;
  console.log(matched);
console.log(percentage);
if(percentage<50)
{
console.log("Change Above 50%");
}
}
Slightly modified first code

JavaScript Syllable Counter - Counting Per Line

Current
I’ve re-worked this syllable counter script to:
Get the value of textarea 1.
Count the number of syllables in textarea 1.
Display the results in textarea 2.
Update the count every time the value of textarea 1 is edited.
Act as a function (be able to run in multiple instances if wanted).
Example function of current code
Input (Textarea 1)
i would appreciate
any help
at all
Results (Textarea 2)
11
Current code
Here is the existing code as a JSFiddle.
Goal
I would like this script to:
Count the syllables of textarea 1 on a per line basis: presumably by splitting the textarea 1 value where there are line breaks e.g. .split('\n');.
Output the results, showing the total number of syllables counted per line.
Example function of desired code
Input (Textarea 1)
i would appreciate
any help
at all
Results (Textarea 2)
6
3
2
Problem
I’m quite stuck as to how to do this and would really appreciate any help or JSFiddle showing how to work with the existing code to achieve this.
Notes
For anyone who may be interested using in the syllable count function code itself: it’s not 100% accurate and fails on some words but gives a good general idea.
Try this and let me know if it's what you needed.
Callouts:
I created an array that spits the lines up stores them var arrayOfLines = $("[name=set_" + $input + "]").val().match(/[^\r\n]+/g);.
Then loop through that array and do exactly what you did before, but on each array entry. Then store the results in tempArr, and display the tempArr results.
See Fiddle
function $count_how_many_syllables($input) {
$("[name=set_" + $input + "]").keyup(function () {
var arrayOfLines = $("[name=set_" + $input + "]").val().match(/[^\r\n]+/g);
var tempArr = [];
var $content;
var word;
var $syllable_count;
var $result;
for(var i = 0; i < arrayOfLines.length; i++){
$content = arrayOfLines[i];
word = $content;
word = word.toLowerCase();
if (word.length <= 3) {
word = 1;
}
if (word.length === 0) {
return 0;
}
word = word.replace(/(?:[^laeiouy]es|ed|[^laeiouy]e)$/, '')
.replace(/^y/, '')
.match(/[aeiouy]{1,2}/g).length;
$syllable_count = word;
$result = $syllable_count;
tempArr.push($result);
}
$("[name=set_" + $input + "_syllable_count]").val(tempArr);
});
}
(function($) {
$count_how_many_syllables("a");
})(jQuery);

Categories

Resources