Compare strings without being case-sensitive - javascript

I have problem with a variable I made (it's a string) in JavaScript. It will be prompt from the user and then with the switch I will check if it is true or not. Then when I input it upper case it will say it is identified as a another var.
Here is my code:
var grade = prompt("Please enter your class") ;
switch ( grade ){
case "firstclass" :
alert("It's 500 $")
break;
case "economic" :
alert("It's 250 $")
break;
default:
alert("Sorry we dont have it right now");
}

Just lower case it initially.
var grade = prompt("Please enter your class").toLowerCase() ;

as #nicael stated just lowercase what they input. However, if you need to preserve the way it was input and only compare using the lowercase equivalent, use this:
var grade = prompt("Please enter your class") ;
switch ( grade.toLowerCase() ){
case "firstclass" :
alert("It's $500");
break;
case "economic" :
alert("It's $250");
break;
default :
alert("Sorry we don't have it right now");
}

You could set the entire string to lower case by using the String prototype method toLowerCase() and compare the two that way.
To keep the input the same, mutate the string during your switch statement:
switch( grade.toLowerCase() ) {
// your logic here
}

You should always compare uppercase string with uppercase values in case sensitive languages.
Or lower with lower.
var grade = prompt("Please enter your class") ;
switch (grade.toUpperCase())
{
case "FIRSTCLASS" :
alert("It's 500 $")
break;
case "ECONOMIC" :
alert("It's 250 $")
break ;
default :
alert("Sorry we dont have it right now");
}

Related

what to put in javascript to know that i input a number?

so i just learned javascript, and learning switch, so i want to know how if i input any number, the alert can know its a number, and the else is anything that not number
var thisVarA = +prompt('a?', '');
switch (thisVarA) {
case 1:
alert('you input number 1');
break
case 2:
alert('you input number 2');
break
case 3:
alert('you input number 3');
break
case 4:
alert('ok this is more than enough');
break
default:
alert('its not just a number');
}
so i want case 4 is if i put any number other than 1,2,3 the alert can know it and put ok its a number
and the else is anything than number even if its has a number ike milano1010
Instead of a switch statement, this would be better for just an if statement.
if (!isNaN(thisVarA)) {
alert('you input number ', thisVarA);
} else {
alert('its not a number');
}
Here we do several things. isNaN checks if it is not a number. We use ! before it to reverse that logic so now we check if it IS a number. The alert starts with 'you input number ' and fills in the number automatically with your variable number instead of needing to check each case. Else is anything that is not just a number like milano1010
Based on your requirements: (switch + determining whether the input is numeric):
<script>
var thisVarA = +prompt('a?', '');
switch (true) {
case thisVarA==1:
alert('you input number 1');
break
case thisVarA==2:
alert('you input number 2');
break
case thisVarA==3:
alert('you input number 3');
break
case Number.isNaN(thisVarA)==false:
alert('ok its a number');
break
default:
alert('it is anything than number');
}
</script>
The Number.isNaN() function determines whether a value is an illegal number (Not-a-Number)
There is a slight sublety in your set up as there is a + immediately in front of your prompt. Javascript takes this to be an arithmetic operation in this situation and therefore forces whatever you input to be of type 'number'. If it were not there the result of your prompt would not be forced to be of type number.
As it is, when you type something like abc123 it is forced to be a number, but it isn't one. Javascript in this situation will give it type 'number' but its value will be NaN (not a number).
Here's your switch with an alert to show you the type and under the default we check whether it's NaN or not.
var thisVarA = +prompt('a?', '');
alert('The type is ' + typeof(thisVarA));
switch (thisVarA) {
case 1:
alert('you input number 1');
break
case 2:
alert('you input number 2');
break
case 3:
alert('you input number 3');
break
default:
if (!isNaN(thisVarA)) {
alert('you input number ' + thisVarA);
}
else {
alert('its not just a number');
}
}

How to have alerts show within a switch [duplicate]

This question already has answers here:
Javascript number comparison fails
(2 answers)
Closed 4 years ago.
I have made a little test program to show the user what bonus they get from having a certain value. The case statements should function as an OR gate. But the problem shows up when the alert should show up on screen but does not.
I have changing a few values, but that did not work. Also new to using JavaScript so I do not know what I can do as of right now.
var strength = prompt("What is the value of strength?");
switch (strength) {
case 10 :
case 11 :
alert("+0");
break;
case 12 :
case 13 :
alert("+1");
break;
case 14 :
case 15 :
alert("+2");
break;
case 16 :
case 17 :
alert("+3");
break;
case 18 :
case 19 :
alert("+4");
break;
case 20 :
case 21 :
alert("+5");
break;
default : ("Please enter a value between 10 and 20");
}
When the user enters the value of strength the bonus of that value should be showing up.
Example: strength = 12 alert("+1")
The alert does not show up though
Prompt returns a string and you are looking for numbers.
var a = 10
switch (a) {
case 10:
console.log("a - yes");
break;
default:
console.log("a - no");
}
var b = "10"
switch (b) {
case 10:
console.log("b - yes");
break;
default:
console.log("b - no");
}
So either you change your switch to be strings, or you change your prompt to be a number. Many ways to do it.
var strength = Number(prompt("What is the value of strength?"));
var strength = parseInt(prompt("What is the value of strength?"));
var strength = +prompt("What is the value of strength?");
Just convert strength to an integer:
var strength = parseInt(prompt("What is the value of strength?"));
switch (strength) {
case 10 :
case 11 :
alert("+0");
break;
case 12 :
case 13 :
alert("+1");
break;
case 14 :
case 15 :
alert("+2");
break;
case 16 :
case 17 :
alert("+3");
break;
case 18 :
case 19 :
alert("+4");
break;
case 20 :
case 21 :
alert("+5");
break;
default : ("Please enter a value between 10 and 20");
}
You are trying to compare a string strength to an int value e.g:10 and this is because prompt is reading as string.
quote from w3schools:
(Returns) a String. If the user clicks "OK", the input value is returned. If the user clicks "cancel", null is returned. If the user clicks OK without entering any text, an empty string is returned.
What you can do is to use parseInt() function to convert the input to an int like so:
var strength = parseInt(prompt("your message: "));
Here's a short modified version:
var strength = parseInt(prompt("What is the value of strength?"));
switch (strength) {
case 11:
console.log("11");
break;
case 12:
case 13:
console.log("+1");
break;
case 14:
case 15:
console.log("+2");
break;
default : ("Please enter a value between 10 and 20");
}

(JavaScript) Using a switch statement with an input box

New to JavaScript so please forgive me if this has an obvious answer. I'm trying to get a switch statement to output a specific phrase depending on the value of an input box, however it will only output the default option. What have I done wrong? Thanks.
<input id="inputIQ" type="number"/>
<button onclick="inputIQFunction()">Submit</button>
<script>
function inputIQFunction()
{
var userinput = document.getElementById("inputIQ").value;
switch (userinput) {
case userinput <= 10:
alert("Less than 10");
break;
case userinput > 10:
alert("Greater than 10");
break;
default:
alert("Please input value");
break;
}
}
</script>
Basically, switch doesn't support conditional expressions. It just jumps to the value according to the cases.
If you put true in the switch (true) part, it'll jump to the case whose have true value.
Try like this
switch (true) {
case userinput <= 10:
alert("Less than 10");
break;
case userinput > 10:
alert("Greater than 10");
break;
default:
alert("Please input value");
break;
}
You cannot use logical conditions in your switch statement. It actually compares your userinput to a result of condition (true \ false), which never occurs.
Use conditions instead:
function inputIQFunction() {
function getIQFunctionOutput(inputValue) {
var parsedInput = parseInt(inputValue);
if (Number.isNaN(parsedInput))
return "Please, enter a correct value";
return parsedInput <= 10
? "Less or equal than 10"
: "Greater than 10";
}
var userinput = document.getElementById("inputIQ").value;
var output = getIQFunctionOutput(userinput);
alert(output);
}
<input id="inputIQ" type="number" />
<button onclick="inputIQFunction()">Submit</button>
P.S. You can actually use switch with logical statements this way:
switch (true) {
case userinput <= 10:
break;
case userinput > 10:
break;
}
but I would highly recommend not to use this approach because it makes your code harder to read and maintain.
Try like this:
<input id="inputIQ" type="number"/>
<button onclick="inputIQFunction()">Submit</button>
<script>
function inputIQFunction() {
var userinput = document.getElementById("inputIQ").value;
userinput = parseInt(userinput);
switch (true) {
case userinput <= 10:
alert("Less than 10");
break;
case userinput > 10:
alert("Greater than 10");
break;
default:
alert("Please input value");
break;
}
}
</script>
A switch works by testing the value of the expression in switch(expression) against the values of each case until it finds one that matches.
In your code, the userinput in switch(userInput) is a string, but your two case statements both have a value of either true or false. So you want to use switch(true) - that's how you get a switch to work with arbitrary conditions for each case. In context:
switch(true) {
case userinput <= 10:
alert("Less than 10");
break;
case userinput > 10:
alert("Greater than 10");
break;
default:
alert("Please input value");
break;
}
I know this is an old thread but I'm just starting out on JS (one week in) and this is the simplest thing I could create just so the logic is understood.
Switch appears to work only by true/false when using a user input value.
My script looks like:
<script>
document.getElementById("click").onclick = function () {
var day = document.getElementById("day").value;
switch (true) {
case day == 1:
document.write("Monday");
break;
case day == 2:
document.write("Tuesday");
break;
default:
document.write("Please enter valid number")
}
</script>
Like I said I'm only a week into this but I'm making a small portfolio for myself with these little things that courses may not teach, I'm open to any one wishing to offer me help learning also, hope it helps with understanding the logic.
You are not fulfilling the requirements of 'switch & case'
userinput <= 10:
It means 'true'
because '<=' is a comparison operator. It compares 'userinput' and ’10'(given value) and give you an answer in boolean(i.e. true or false).
But, here in switch case you need an integer value.
Another
You have entered this
'switch (userinput)' here 'switch' considering 'userinput' a string that should be integer,
You can fix it with this.
switch (eval(userinput))

Switch statement compare user input Javascript

I'm trying this simple code and seems like the user's input is not going through all the comparisons and jumps to the default one right away. I'm guessing that JS is taking the user's input as a string instead. I did try to parseInt() but didn't work. Here is my code;
var number = prompt('What\'s your favority number?');
switch(number){
case (number < 10):
console.log('Your number is to small.');
break;
case (number < 100):
console.log('At least you\'re in the double digits.');
break;
case (number < 1000):
console.log('Looks like you\'re in three digits.');
break;
default:
console.log('Looks like you\'re in the fouth digits.');
}
Use true as an expression for switch.
The switch statement evaluates an expression, matching the expression's value to a case clause, and executes statements associated with that case.[Ref]
A switch statement first evaluates its expression. It then looks for the first case clause whose expression evaluates to the same value as the result of the input expression (using strict comparison, ===) and transfers control to that clause, executing the associated statements. (If multiple cases match the provided value, the first case that matches is selected, even if the cases are not equal to each other.) . If no matching case clause is found, the program looks for the optional default clause, and if found, transfers control to that clause, executing the associated statements.
var number = prompt('What\'s your favority number?');
number = Number(number); //Use `Number` to cast it as a number
switch (true) {
//----^^^^
case (number < 10):
console.log('Your number is to small.');
break;
case (number < 100):
console.log('At least you\'re in the double digits.');
break;
case (number < 1000):
console.log('Looks like you\'re in three digits.');
break;
default:
console.log('Looks like you\'re in the fouth digits.');
}
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
Edit: As suggested by #bergi in the comments, an if/else cascade is the best approach for this problem.
var number = prompt('What\'s your favority number?');
number = Number(number); //Use `Number` to cast it as a number
if (number < 10)
console.log('Your number is to small.');
else if (number < 100)
console.log('At least you\'re in the double digits.');
else if (number < 1000)
console.log('Looks like you\'re in three digits.');
else
console.log('Looks like you\'re in the fouth digits.');
You're not understanding how the switch statement works. It is not a shortcut for checking dynamic values. It's a shortcut for checking known values.
Each case is a statement that gets evaluated to a value. If you look at the docs, you'll see that they have case: value, rather than what you are attempting, which is case: (expression). So, it's going to turn all your expressions into values.
So, for example, your first case is:
case (number < 10):
But what that really becomes is:
case false:
And of course, no number will evaluate to false (technically 0 is a falsey value, but the switch uses === comparison rather than == so 0 === false // false). Thus, all your cases are really case false, and so the switch is falling through all of them and landing on the default case.
So, for your situation, the switch statement is inappropriate. You should use if statements.
if(number < 10) {
} else if(number < 100) {
} else if(number < 1000) {
} else {
}
The switch statement is only appropriate when you know the values:
switch(number) {
case 10:
break;
case 100:
break;
case 1000:
break;
default:
}
(And yes, use parseInt to ensure you have integers.)

Switch Test if isNan

In a switch statement, I want make sure the user did not type a number. I get an error with this:
"case !isNaN(user):"
var user = prompt("Hey! What do you like?","").toLowerCase();
switch(user){
case "":
console.log("Can\'t be blank!");
break;
case !isNaN(user):
console.log("Can\'t be a number");
break;
case "food":
console.log("Food does a body good...sometimes");
break;
default:
console.log("Mmm....Can\'t Make heads or tales of this one.");
}
I tried this too, but not working:
switch(!isNaN(user)){
case true:
console.log("Hey! Can\'t be a number!");
break;
I can get !isNaN to work in an else if, but not in a switch.
var user = prompt("Hey! What do you like?","").toLowerCase();
if(!isNaN(user)){
console.log("Can\'t be a Number!");
}
The switch statement is comparing your user variable to each case. so it has to be read like
does user == "". Yes? do stuff
does user == "food". Yes? do stuff
otherwise, do stuff
when you read a case statement like this, you'll realise why your NaN case doesn't work
does user == isNaN(user) <- will never be true
Your final code is the way you need to do it
var user = prompt("Hey! What do you like?","").toLowerCase();
if(!isNaN(user)){
console.log("Can\'t be a Number!");
}

Categories