Making a simple HTML calculator issue in Javascript - javascript

I am learning Javascript and I am trying to make a simple HTML calculator where 2 prompts appear asking for numbers to add. Anytime I execute I get just the 2 numbers added together like 2 + 2 = 22, I did something wrong because I would want the response to be the right answer. Thanks so much!
'use strict';
let txt = prompt('Please enter your calculation');
let cal = prompt('And the other one');
let orange = txt;
let apple = cal;
alert(orange + apple);

Your prompt inputs (txt and cal) are strings... you need to parse them to integers
let txt = prompt('Please enter your calculation');
let cal = prompt('And the other one');
let orange = parseInt(txt); let apple = parseInt(cal);
alert(orange + apple);
if you also want to add floats, use parseFloat() instead of parseInt()

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)

how can i put a period at the end of a formated text

hi this is my first question, sorry if it is stupid but i stumble upon this code
function format(input){
var num = input.value.replace(/\./g,'');
if(!isNaN(num)){
num = num.toString().split('').reverse().join('').replace(/(?=\d*\.?)(\d{1})/g,'$1.');
num = num.split('').reverse().join('').replace(/^[\.]/,'');
input.value = num;
}
else{ alert('just numeric values please');
input.value = input.value.replace(/[^\d\.]*/g,'');
}
}
i don't really understand how it works, but basically it formats an input in real time to this format "9.9.9.9.9" but i want it to have it like this "9.9.9.9.9.". How can i add that last period?
thanks beforehand
If all you need to do is add the period to the end of the string, just do:
num + ".";
For your entire function, if you are taking a string like "12345" and just want to put a period after each number and at the end, then there are easier ways to do it than what you have:
text = text.replace(/(.)/g, '$1.');
Will do it.
input.value = num+'.';
or like this
var num = b.split('').reverse().join('').replace(/^[\.]/,'').replace(/$/, ".");
/$/ means end of the string
or like this
var num = b.split('').reverse().join('').replace(/^(.{1})(.+)/, '$2$1');
Take a look at this post:
Move n characters from front of string to the end
enjoy

Issue with passing property through function

First off my apologies if I did something incorrectly with asking a question, I'm very new to stackoverflow and javascript as well. I am having an issue with passing a property through my getPassword function and I've searched around and couldn't truly pinpoint an answer. The code I created is designed for an object called "student" with two properties; FirstName and LastName.
Using a couple of dialogue boxes the information related to each student is entered. At the end, a prompt should display and asks the user "Do you want to add more student?" If the answer is "Yes", It asks the next student's information. If the answer is anything else, It stops asking. Then the information is displayed on the webpage. I want to have a property called "UID" The format of UID is FirstName_PSWD. For calculating the "PSWD" the function called "generatePassword" is used. This function randomly creates a 6-digit password including characters and numbers. For example: if username is John, then UID may be "John_X12bn231". I can not seem to get this password function to work, what might I be doing wrong? I am also aware that there might be other errors in my code, which I do apologize for i am very much a beginner.
var student={FirstName:"", LastName:""};
var studentlist=[];
var i=0;
function generatePassword() {
var length = 4,
charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
retVal = "";
for (var i = 0, n = charset.length; i < length; ++i) {
retVal += charset.charAt(Math.floor(Math.random() * n));
}
return retVal;
}
function Register() {
var next="Yes";
while (next="Yes"){
student.FirstName=prompt("Please enter the name");
student.LastName=prompt("Please enter the last name");
studentlist.push(student);
document.getElementById("demo").innerHTML += "<li> <b>First Name:</b> "+ studentlist[i].FirstName + "," +
"<b>Last Name: </b>"+ studentlist[i].LastName + "," + "</li>";
next = prompt ("Do you want to add more data?", "Yes")
i++;
}
}
Two mistakes:
var student={FirstName:""; LastName:""};
Should be -> var student={FirstName:"", LastName:""};
var i==0; -> var i = 0;
Try after changes and tell me if it works ;d
Btw. Javascript is a frontend. Your users will be able to check how you generate the password, because all your code can be read.

"parsing" a text document to specific javascript format?

Edit - I think parsing it the wrong word to use, I'm actually looking to format that text file into the format I provided.
I'm working on a project and I've ran into a slight problem. I need help with mass editing a text file into a certain format. I don't really know how to do this. For example, here is the text file: http://frankerfacez.com/users.txt
That has the list of users and emotes (users without periods, emotes with). I would need that to be changed into the format of
//user
"emote":["cdn.frankerfacez.com/channel/ user / emote.png"],
For reference, this is what I need the format to be: https://dl.dropboxusercontent.com/u/23313911/CustomEmotes.js
I really don't know how easy this will be or if it is even possible, but any help would be greatly appreciated!
lines = txtFile.responseText.split("\n");
var user = null;
var emote = null;
var o = {};
for (i in lines) {
var line = lines[i];
if (line.charAt(0) != ".")
user = line;
else {
try{
emote = line.substring(1, line.legth);
var a = new Array();
eval("var cnd = new String('cdn.frankerfacez.com/channel/'+user+'/'+emote+'.png');");
a.push(cnd.toString());
eval("o."+emote+" = a;");
}catch(e){
console.error(emote + " - " + user);
console.error(e);
}
}
}
console.log(o);

Adding User input without rounding (Google Apps Script)

I am adding a users input in to UI as they add numbers and returning the results. The input is currency so I need to carry it out two decimals and not round.
Here is an example of my code:
function ceiling2(number) {
var ceiling2;
return ceiling2 = Math.ceil(number*100)/100;
}
//Totals
function lD23Total (e){
var app = UiApp.getActiveApplication();
var tB1v = parseInt(e.parameter.TextBox1);
var tB9v = parseInt(e.parameter.TextBox9);
var tB17v = parseInt(e.parameter.TextBox17);
var tB25v = parseInt(e.parameter.TextBox25);
var tB33v = parseInt(e.parameter.TextBox33);
var tB41v = parseInt(e.parameter.TextBox41);
var tB49v = parseInt(e.parameter.TextBox49);
var lD23 = app.getElementById("LabelD23").setStyleAttribute('fontWeight','bold');
var lD23T = tB1v + tB9v + tB17v + tB25v + tB33v + tB41v + tB49v;
lD23.setText("$ " + ceiling2(lD23T));
var app = UiApp.getActiveApplication();
app.close();
return app;
}
Currently it returns a rounded number.
I appreciate an suggestions you may offer!
Jon
The function parseInt() will convert the value to an integer, dropping the values after the decimal. Use parseFloat() instead.
I think your function is just fine...
if you remove the parseInt() and replace it either with parseFloat()as suggested by Eric or by Number() it should work...
if not then the problem might come from the way numbers are written:
If you used 26,4567 but you should use 26.4567 with a dot as separator in place of a comma.
Could you try and keep us informed ?
regards,
Serge
Or you can use this before sending to your function:
var newnumber=Number(number.toString().replace(",","."));// convert to string, replace comma with dot and set as number again.
and your function will work in both cases

Categories

Resources