I just learned about the prompt() command; I know that the prompt() command returns user input in the form of a string. I was messing with the program below, and I typed in Per "Dead" Ohlin for the male name. Why did this work and not cause any problems? "Per "Dead" Ohlin..." should have caused a problem. Does the interpreter automatically fix this by putting an escape character before the quotation marks?
let nameOfTheKiller = prompt("Type in a male name.");
let nameOfTheVictim = prompt("Type in a female name.");
let nameOfDrug = prompt("Type in the name of a drug.");
let nameOfAlchoholicBeverage = prompt("Type in the name of an alchoholic beverage.");
let story = nameOfTheKiller
story += " went to a diner, met "
story += nameOfTheVictim + ", and asked her to hangout."
story += " She said yes, so " + nameOfTheKiller + " took her home. As soon as they arrived to "
story += nameOfTheKiller + " relax-location, " + nameOfTheKiller
story += " pulled out " + nameOfDrug + " and " + nameOfAlchoholicBeverage + ". "
story += nameOfTheKiller + " and " + nameOfTheVictim
story += " started using the party favors and got really high and drunk. The party favors gave "
story += nameOfTheKiller + " auditory halucinations that comanded him to kill "
story += nameOfTheVictim + ", so he did." ;
alert("We are done asking you questions. We are generating a story for you. The story will be finished, shortly.");
document.write(story) ;
prompt is not eval - whatever you pass to it will be interpreted as a string. Typing in
Per "Dead" Ohlin
when this line runs
let nameOfTheKiller = prompt("Type in a male name.");
is like doing
let nameOfTheKiller = `Per "Dead" Ohlin`;
Any characters you include in the string you enter which happen to also be valid string delimiters in Javascript will be interpreted as those literal characters (", ', backtick), rather than as delimiters.
Related
I've just started learning how to code in JS and I wanted to make a program that greets the user after he fills the information needed age and name.
I added a loop that checks if provided data typed in the prompt is a number but it seems to go on infinitely, like the value was always wrong and the loop looped itself over and over even if the value was right (of course after I firstly typed in the wrong value).
The best part is when I display the typeof value it shows it's right and wrong at the same time.
alert("Hi this site is only accsesable by pepole above an age of 18")
let usersAge = prompt("How old are you?");
usersAge = Number(usersAge);
while (Number.isNaN(usersAge)) {
let usersAge = prompt("type in the correct value?");
}
if (usersAge >= 18) {
let userName = prompt("cool,what is ur name")
toString(usersAge)
console.log("wassup" + " " + userName + " " + "with age of" + " " + usersAge)
} else {
console.log("sorry ur age is to low for us to display this website")
};
console.log(typeof usersAge)
console.log(usersAge)
Console output:
sorry ur age is to low for us to display this website
"number"
NaN
The first issue is because you're redefining usersAge within the while block, which affects the outcome of that loop. Remove the let keyword there.
The other issue is that you're comparing strings to integers in some cases. Cast all values to the same type before comparison.
With those issues addressed your code works:
alert("Hi this site is only accsesable by pepole above an age of 18")
let usersAge = parseInt(prompt("How old are you?"), 10);
while (Number.isNaN(usersAge)) {
usersAge = parseInt(prompt("type in the correct value?"), 10);
}
if (usersAge >= 18) {
let userName = prompt("cool,what is ur name")
toString(usersAge)
console.log("wassup" + " " + userName + " " + "with age of" + " " + usersAge)
} else {
console.log("sorry ur age is to low for us to display this website")
};
console.log(typeof usersAge)
console.log(usersAge)
However putting a prompt() in a potentially infinite loop is a really bad design choice. The kind which will infuriate your users and get your site blacklisted.
A better approach would be to validate the input and if it's invalid then you should give the user the choice to cancel out of the loop and leave your site. Right now you're forcing the user to enter an age before they can leave.
Hi my friend to fix your problem you need to not use let because you use it once.
I'm going to give you the right syntax for your problem :
alert("Hi this site is only accsesable by pepole above an age of 18");
let usersAge=prompt("How old are you?");
usersAge = Number(usersAge);
while(Number.isNaN(usersAge) || usersAge === null || usersAge === '') {
usersAge= prompt("Enter your age")
}
{
if( usersAge >= 18){
let userName = prompt("cool,what is ur name");
toString(usersAge)
console.log("wassup" + " " + userName + " " + "with age of" + " " + usersAge)
}
if( usersAge < 18){
console.log("sorry ur age is to low for us to display this website");
} else{
usersAge = prompt("type in the correct value?")
}
}
I hope your problem was solved.
I have two html datalists, and I get their input values to query a json file. I first search the keys of my json file which are college majors, their values are their courses. So once the object key equals the program, I return that element because I want to further query that element with the second input field which is a course number. This step is always successful at returning the correct program courses corresponding to the program input.
The second step is where things go bad. I want to now take that program element and look through all the names of the courses in that program. I concatenate the two input fields, program + " " + course. The program is a major like "CSE" or "I S" and the course is any 3 digit number like "143" or "310". Each object element in the program has a string name attribute like "CSE 143". This name attribute does not equal the program + " " + course even though they are both of type string and the same value WHEN I am looking at a program that has a space in it. For example, I want to find the course "I S 310". I successfully search for the program name that equals "I S". I iterate through the keys and find the correct element value using this operation Object.keys(jsondata[index]) == program. program is a variable containing the string "I S". As stated previously, this is successful, but if I iterate through the children of that objectkey value to find id, like programdata[index].children == program + " " + course, it doesnt work. If I instead hardcode the value, programdata[index].children == "I S 310", it works! This leads me to believe that the concatenation operation for these two variables changes the encoding of the string. According to console.log, the type of "I S 310" and program + " " + course are both Strings except they output a different encodeURIComponent().
Ill write what the output to the console is since im not reputable enough:
Step 1
function getProgramCourses(data, program) {
var programKeys = Object.keys(data);
for (var i = 0; i < programKeys.length; i++) {
if (Object.keys(data[i]) == program) {
return data[i][Object.keys(data[i])];
}
}
return objs
}
program = "CSE"
console.log(program)
console.log(encodeURIComponent(program));
Output:
CSE
CSE
program = "I S"
console.log(program)
console.log(encodeURIComponent(program));
Output:
I S
I%C2%A0S
Those unencoded hidden characters dont affect this first step of finding the courses offered by the "I S" program. Now when I want to find a specific course within the "I S" program like "I S 310":
Step 2
//data is object array of all courses in this program
function getCourse(data, program, course) {
pc = program + " " course;
for (var i = 0; i < data.length; i++) {
if (data[i].name == pc) {
return data[i];
}
}
}
"CSE" = program and "143" = course
pc = program + " " + course;
console.log(pc)
console.log(encodeURIComponent(pc));
Output:
CSE 142
CSE%20142
["I S" = program and "310" = course][2]
pc = program + " " + course;
console.log(pc)
console.log(encodeURIComponent(pc));
Output:
I S 310
I%C2%A0S%20310
This second step only works for programs that dont have spaces like "CSE" or "MATH". Doesnt work for "A A" or "I S". data[i].name is type String and so is pc.
Sorry about the lengthy post, I just wanted to be as descriptive as possible. Any help would be greatly appreciated.
Basically
Here is my problem:
console.log("A A 198")
console.log(encodeURIComponent("A A 198"))
console.log(program + " " + course)
console.log(encodeURIComponent(program + " " + course))
Output:
A A 198
A%20A%20198
A A 198
A%C2%A0A%20198
not equal
Your program variable contains a character which is like a space but isn't a space. Make sure it isn't an encoding issue, else you can fix this with this simple code.
encodeURIComponent(program.replace(/\u00a0/g, ' ') + ' ' + course)
I am playing with some basic js I am just beginning to learn, so far I have the code below. I am trying to ask the user what their name is and then tell them if they share the same name as a racing driver (from my array driversNames).
If they have the same name as a racing driver it would tell them they do, if not it would tell them they don't. However I have a feeling I have something wrong here: if (yourName === driversNames) but I cannot figure it out.
It doesn't matter what I enter into the prompt, it always says sorry you don't have the same name.
var driversNames = ["Lewis", "Fernando", "Sebastian", "Jenson", "Daniel"]
for (var i = 0; i < driversNames.length; i++) {
console.log(driversNames[i] + " " + "is a drivers name");
}
var yourName = prompt("What is your name?")
console.log("Your name is" + " " + yourName)
if (yourName === driversNames) {
console.log("Awesome" + " " + yourName + " " + "you share the same name as a Formula 1 driver!")
} else {
console.log("Sorry" + " " + yourName + " " + "you don't have the same name as any Formula 1 drivers")
}
You made one mistake in this line if (yourName === driversNames).
It doesnt compare your name with names from driversNames. The most easiest way: its use indexOf method. So this line should be like below
if (driversNames.indexOf(yourName) > -1) //Get Name otherwise no
And jsfiddle example for you, also indefOf link
Thanks
You are comparing a string to an array, so the comparison will return false. You have a few options to fix this though - I'll explain using a loop to check each string, and using indexOf.
Loop: You need to loop through each element in the driversNames array and compare each one. This is the manual way.
var sameName = false; //flag to keep track of if name matches or not
driversNames.forEach(function(name) { //loop through each name in driversNames
if(yourName === name) { //compare your name to driver name
sameName = true; //if match, set flag to true
}
}); //loop ends here
if(sameName) { //if flag is true, a name matched
console.log("Awesome" + " " + yourName + " " + "you share the same name as a Formula 1 driver!"); //Console log success statement
} else { // else, no name matched
console.log("Sorry" + " " + yourName + " " + "you don't have the same name as any Formula 1 drivers"); //console log fail statement
}
IndexOf: This method uses less lines of code, but isn't compatible on all browsers - I believe anything under IE8 will break when using this for example. But if compatibility isn't an issue, it looks like this:
if (driversNames.indexOf(yourName) > -1) { //indexof returns -1 for no match, and a number for match
console.log("Awesome" + " " + yourName + " " + "you share the same name as a Formula 1 driver!"); //console log success statement
} else {
console.log("Sorry" + " " + yourName + " " + "you don't have the same name as any Formula 1 drivers"); //console log fail statement
}
indexof is a little more elegant, although easy to forget the compatibility issue. Code is commented but just to explain it: Arrays have a method you can call, called indexOf() which takes a parameter. This method will then check if that parameter is in the array and if it is, return a value which is it's position in the array. If it isn't in the array, it will return -1.
I'm trying to monospace bibleverse references so that single digit chapters or verses have a leading space.
So "4:5" becomes " 4: 5" and "3:21" becomes " 3:21".
I'm really having problems writing the regex, please help.
I've tried many variations but they essentially boil down to (^\d|\d$), (^\d{1}|\d{1}$) and (^[^0-9]\d|[^0-9]\d$) and many combinations between them
inRef = inChapter + ':' + inVerse;
var inReg = /(^[0-9]{1}|[^0-9][0-9]{1}$)/g;
inRef = inRef.replace(inReg," $1");
console.log(inRef);
Alot of the results I'm getting from my efforts turn references like "6:15" into " 6: 1 5" or " 6:1 5"
Thank you in advance.
Why a regex at all? You've already got the chapter/verse as separate data BEFORE you combined them into the x:y format, so do the formatting there while they're still seperate strings:
if (inChapter.length == 1) { inChapter = ' ' + inChapter }
inRef = inChapter + ':' + inVerse;
Using a regex for this uber-simplistic transformation is akin to nuking a city to get some dust off a shelf instead of using a feather duster.
Given the strings inChapter and inVerse, you could do something like this:
inRef = (" " + inChapter).slice(-2) + ":" + (" " + inVerse).slice(-2)
Note there are two spaces there " " and I'm assuming inChapter and inVerse are only ever 1 or 2 digits.
Edit: Since you need three digits and I assume you still want these to line up, you could do this:
var pad = " "; // this is now THREE spaces!
inRef = (pad + inChapter).slice(-pad.length) + ":" + (pad + inVerse).slice(-pad.length)
So now if you run all your inChapter and inVerse pairs through this, you should get strings that line up like this:
100:100
20:100
2:100
100: 10
100: 1
10: 10
10: 1
1: 1
I'm trying to create a prompt that has a time delay, the value that is written in the prompt is then used in other areas of the form. I have written some javascript coding but I believe there is a minor thing that i am doing wrong as currently the prompt and delay are working, but because the setTimeout function is being used, that is what is being displayed in the form, instead of the content of the prompt. This is my Javascript?
var name = setTimeout(function(){ prompt("What is your name?", "Type your full name here")},750);
document.write("Document Written By: " + name + " (" + day + "/" + month + "/" + year + ") ")
If it depends on the value, and a function is asynchronous, you've got do it in the callback. Just like every other asynchronous piece of JavaScript...
setTimeout(function(){
name = prompt("What is your name?", "Type your full name here");
document.write("Document Written By: " + name + " (" + day + "/" + month + "/" + year + ") ");
},750);
But as #Jon commented, please do not use document.write.