Allowing both lower and uppercase when doing quiz application in JavaScript? - javascript

I am currently doing a quiz in JavaScript and would like it so that the user could type using lowercase or uppercase but it does not effect the result. I have had a look about but I'm struggling to see anything that could help. (I know to add a question, and of course the correct answer - which I am currently developing). Thank you.
function Quiz()
{
var answer = prompt("question here?","");
if (answer=="your answer here")
{
alert ("Correct!");
}
else
alert ("Incorrect");
}

You can convert both sides to lower case by using String.prototy.toLowerCase() function. This will insure that both strings are lower case.
function Quiz()
{
var answer = prompt("question here?","");
if (answer.toLowerCase()=="your answer here".toLowerCase())
{
alert ("Correct!");
}
else
alert ("Incorrect");
}

You want to call String.prototype.toLowerCase on answer. This converts everything with lower case letters so you can compare easily:
if (answer.toLowerCase().trim() == "your answer here".toLowerCase()) {
// ...
}
The trim function removes trailing and leading whitespace in case the user accidentally enters some.

Related

In a series of prompts, need to keep asking the last prompt over and over until answer

I'm creating a joke script for a site that does a series of prompts asking the user if they agree I know javascript. After they answer negative the first time, a slightly modified version of the question is restated. And finally a mocking version of the question is asked and if answered negatively will just ask it again and again until it's answered yes. I can get to the last part just fine. But I can't figure out how to get the code to go back to the last question over and over again and then switch to "thank you" response after they finally are forced to say yes. any help would be appreciated.
my code:
javascriptExample.addEventListener("click", function(){
const answer = prompt("This prompt was created using Javascript. Are you now satisfied we know Javascript? Y/n: ");
if (answer == "n") {
answerTwo = prompt("Sigh. Fine. What about now? Y/n: ");
if (answerTwo = "n") {
do{
const answerThree = prompt("Look, I can do this all day long. So, why don't you knock it off and just go ahead and say yes already, okay? Y/n: ");
} while(answerThree == "n");
} else {
alert("About time. Thank you for your cooperation and vote of confidence. I'm wasn't sure I could've kept it up forever.");
}
} else {
alert("Thanks for the vote of confidence. You're a real mensch!");
}
});
while(["A","B","C"].every(el=>!confirm(el))){}
alert("Fine");
A,B and C are your questions. Just a bit shortified...
If you wanna keep your exact answer structure:
if(confirm("A") || confirm("B")){
alert("nice of you!");
return;
}
while(true){
if(confirm("C")){
alert("youve got it");
return;
}
}
Note that variables defined using an ES6 const or let are block scoped rather than function scoped like variables defined using var.
For this reason, answerThree is no longer is scope inside the while condition and the comparison fails.
Instead, define the variable before the loop:
let answerThree;
do {
answerThree = prompt("Look, I can do this all day long. So, why don't you knock it off and just go ahead and say yes already, okay? Y/n: ");
} while (answerThree == "n");
This will lead to your desired result. Also note that you cannot reassign consts, which is why a let needs to be used here.
switch to "thank you" response after they finally are forced to say yes
This does not seems like a great idea to me because people might feel annoyed and really want to skip this question!
get the code to go back to the last question over and over again
However if you need to ask multiple questions in multiple patters than I would suggest to store questions in an array (a 2D might be more helpful)
var question = {
'1' : {
'1' : 'joke1.1',
'2' : 'joke1.2'
},
'2' : {
'1' : 'joke2.1',
'2' : 'joke2.2'
}
};
question_no=2;
question_version=1
if (answer == "n") {
question_version++;
prompt( question_no[question_no][question_version]+ Y/n: ");
}else{
question_no++;
}

How do I create a function that checks if a date is a palindrome?

My question has two parts. I'm trying to check whether a date is a palindrome or not. In the following code, I continuously get the result of "Not a palindrome" even if the string is in fact a palindrome.
function isPalindrome(str){
var rev = str.reverse;
if(str === rev){
console.log("This is a palindrome.");
}
else{
console.log("Not a palindrome");
}
}
isPalindrome("2002");
The second part to my question is: if I wanted the function to take two arguments function isPalindrome(start_date, end_date)and have it check the dates between for palindrome years and then return those years chronologically, how do I do that? I'm not asking for anyone to actually do it for me. I'm just asking for an explanation on how to accomplish it.
Thanks in advance.
It could be something with the reverse function you are using. You could output the value of rev to see what's going one.
I would suggest you use this: How do you reverse a string in place in JavaScript?
I'm not familiar with any string reverse() function in anybody's native javascript implementation. But here's something I wrote a while back that does the palindrome thing, fwiw:
String.prototype.reverse = function (){
//Another way to reverse a string is to use Array's reverse:
// "this.split('').reverse().join('')";
//but that's boring, and recursion is fun!
if (this.length < 2) { return this.toString() };
return this.slice(-1) + this.slice(0,-1).reverse();
}
String.prototype.is_palindrome = function (){
return this.toString() === this.reverse();
}
This checks whether a string is a palindrome.
As for the second part of your question, I'm not sure how to do that off the top of my head. I would start by seeing what's natively available via javascript's Date object. Check MDN. You would only have to handle the years, so I'd just figure out the year range first and iterate over that, checking for palindromes along the way.
Are you stripping out the non-numeric characters first?
var strippedDate = str.replace(/[^\d]/g, "");
return strippedDate == strippedDate.reverse();

mark a specific word after each space

I'm trying to warning the user if he types a word that is not necessary in a textarea.
its just a little validation for some words.
i reach making something like this:
var words = "hello";
$("textarea").keyup(function(e){
var spliting = $("textarea").val().split(" ");
if(e.keyCode == 32){ // when the user hits space bar
if($.inArray(words, spliting) != -1){
$("span").css("background","red");
}else{
$("span").css("background","green");
}
}
});​
is this the best way of doing this ?
and how can i migrate the variable words as a array, if i need to check more then one word?
Demo
To use an array, you will need to loop over each word in it and loop over each word in the split array. However, you can return on the first match:
var words = ["hello","goodbye"];
$("textarea").keyup(function(e){
var spliting = $("textarea").val().split(" ");
for (var i=0; i<words.length; i++) {
if($.inArray(words[i], spliting) != -1){
$("span").css("background","red");
// break on first match since there is no need to continue looping
// if it is already red.
break;
}else{
$("span").css("background","green");
}
}
});​
I have removed the check for spaces. Even though it makes the function more efficient, you need to be wary of cases when someone goes back to correct spelling and ends up with an invalid word. The way you had it, those cases would never cause the flagged words to be found unless a space was typed later.
It would be advisable to call this function for onchange and blur events as well, since typing is not the only way users enter input into form inputs.
Here is the updated demo
You don't need to .split the input every time a key is pressed, this is a situation where a regular expression is to be preferred:
Check the updated fiddle
To generate the expression based on an array:
var blackList = ['hello','world'];
var expression = new RegExp('\\b(' + blackList.join('|') + ')\\b','i');
$("textarea").keyup(function(e)
{
//if (e.keyCode === 32)
//{in comment after reading the answer posted by Michael Berkowski
if ($(this).val().match(expression))
{
$("span").css("background","red");
return;
}
$("span").css("background","green");
//}
});​

Regexp Numeric with Single Decimal

I've written the following js with regexp. It works as expected, however I'm looking to simplify it. Could somebody help me out?
.12345 - success
0.12345 - success
12345.12345 - success
0.123456 fail - this I wish was dynamic and not restricted to 5
1.123.45 fail
1.. fail
.. fail
abc - fail
function clearNonNumericChars(field) {
field.val(field.val().replace(/([^0-9\.])/g,""));
field.val(field.val().replace(/^(\d*\.[0-9]{5})\d+$/g,"$1"));
field.val(field.val().replace(/(\.\d*)(\.)$/g,"$1"));
}
Don't deal with numbers as strings.
isNumberValid = function(n) {
return (n == Math.round(n*10000)/10000)
}
You don't need a regex if you don't want one, if you are doing this on keyup. Just filter by keycode/which in your event handler. You've marked the question jQuery, so:
$('input').on('keyup', function (e) {
if ($.inArray(e.which, [48,49,50,51,52,53,54,55,56,57,190]) === -1) {
return true;
}
return false;
});
Note I haven't really tested this, but this basically makes it so the user can't enter anything but numbers or the decimal. Note that they can still paste bad characters in. I'll leave the solution for that to the reader...
Is this what you are looking for? >>
var str = "1a2..b3.C4;56";
str = str.replace(/[^0-9\.]/g,"").replace(/\./,",").replace(/\./g,"").replace(/,/,".");
print(str);
Live test at http://ideone.com/F7wWV

Exact string match with javascript regex

I'm struggling with what is probably a very simple regex problem. I'm working on a simple prototype and need to know what page I'm on, so I don't reload it if the user clicks a menu widget to navigate to the same view.
I have two URLs the user can switch between:
http://localhost/TestMVC/Larry/LarryTiles
http://localhost/TestMVC/Larry/LarryTilesList
The URLs can also have some trailing querystring items, like this:
http://localhost/TestMVC/Larry/LarryTilesList?filterValue=servers
LarryTiles is giving me the problem. "/\bLarryTiles\b/" worked on Friday (after answers from other questions here) but this doesn't match now. :)
I need to find exactly the strings "LarryTiles" and "LarryTilesList" in these two URLs but can't quite figure out how to do that. The URL changes between my local machine and the various servers where it's hosted, so I can't rely on position.
EDIT: added the example with a trailing querystring, which I'd forgotten. Sorry :(
You can get the last path segment of an URL like this:
function getLastPathSegment(url) {
var match = url.match(/\/([^\/]+)\/?$/);
if (match) {
return(match[1]);
}
return("");
}
// returns "LarryTiles"
getLastPathSegment("http://localhost/TestMVC/Larry/LarryTiles");
// returns "LarryTilesList"
getLastPathSegment("http://localhost/TestMVC/Larry/LarryTilesList");
So, you could do this:
var endPath = getLastPathSegment(window.location.pathname);
if (endPath == "LarryTiles") {
// some code
} else if (endPath == "LarryTilesList") {
// some code
} else {
// some code
}
You can use this code:
str = 'http://localhost/TestMVC/Larry/LarryTiles?filterValue=servers';
if (str.match(/\/([^\/?]+)(?=\/$|\?|$)/)) {
if (match[1] == 'LarryTiles')
alert('LarryTiles found');
else if (match[1] == 'LarryTilesList')
alert('LarryTilesList found');
}
Seems like what you explained works, otherwise try this: http://jsfiddle.net/Wfz9d/
Do you have a case-sensitivity issue?

Categories

Resources