My friend is working on a fun Javascript web application where you type something in the text box, and the computer returns you a result, but it is case-sensitive. Can he make it case-insensitive? We have tried to use:
var areEqual = string1.toUpperCase() === string2.toUpperCase();
which was on JavaScript case insensitive string comparison, but he cannot figure out how to use that.
function isValid() {
var password = document.getElementById('password').value;
if (password == "Shut Up")
{ alert('HOW ABOUT YOU!') }
else if (password == "No")
{ alert('You just did') }
}
Please, if you're going to do this, use switch! The only real difference between toLowerCase as opposed to toUpperCase here is that the values in the case lines won't be shouting at you.
function isValid() {
var password = document.getElementById('password').value;
switch (password.toLowerCase()){
case "shut up":
alert('HOW ABOUT YOU!');
break;
case "no":
alert('You just did');
break;
case "okay":
alert('Okay');
break;
// ...
case "something else":
alert('Really?');
break;
default:
alert('Type Something Else')
}
}
Just add the .toUpperCase() behind your variables:
else if (password == "No")
{alert('You just did')}
becomes:
else if (password.toUpperCase() == "No".toUpperCase())
{alert('You just did')}
or just:
else if (password.toUpperCase() == "NO") //Notice that "NO" is upper case.
{alert('You just did')}
You can use that this way, for example in the first else-if block:
else if (password.toUpperCase() == "No".toUpperCase())
{alert('You just did')}
The function toUpperCase, applied to a string, returns it's uppercased version, so for No it would be NO. If the password variable holds any lower-upper case combo of the word no, such as "No", "nO", "NO" or "no", then password.toUpperCase() will be "NO".
The previous code is equivalent to
else if (password.toUpperCase() == "NO")
{alert('You just did')}
Related
Very basic javascript, i'm a complete beginner trying to construct an if statement to check if a variable is a specific letter
more specifically, if a user input for a variable is "P", "M" or "G"
i'm using
if (variable = P) {
statement
}
but doesn't seem to be working
thanks in advance
In addition to forgetting the quotes around the letter "P", you've used the assignment operator =, instead of the comparator ==.
Check this out:
var name = "Carolyn";
console.log(name);
# "Carolyn"
var name_is_carolyn = (name == "Carolyn");
console.log(name_is_carolyn);
# true
Changing your code to this should help:
if (variable == "P") {
// statement
}
if(variable == 'P' || variable == 'G' || variable == 'M') {
// do something
}
take care, it's case sensitive without using toLowerCase or toUpperCase on the string.
anther way is:
switch(variable.toLowerCase()) {
case 'p':
// do something for p
break;
case 'm':
case 'g':
// do something for m and g (no break; in m case)
break;
default:
// no match, so do something else
}
Here's how you can do it in JS:
TextLetter=function(txt,letter){
try{
var TXT=txt.split(letter);
if(TXT.length>0)
return true;
else
return false;
}catch(err){
return false;
}
}
TextLetter(prompt("Type in text","TEXT"),prompt("Look for the character or phrase...","?"));
I didn't test this yet, but should be helpful
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))
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");
}
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!");
}
var t = "TEST";
switch(t){
case !"TEST": /* <- does not work. Can you check if t does NOT contain a string? */
alert("t != TEST");
break;
}
Can you do this with a switch statement?
you can also do this:
var str = "TEST";
switch (true) {
case (str !== "TEST") :
alert("str !== TEST");
break;
case (str === null) :
alert("str is null");
break;
default:
alert("default trigger");
}
You can use if. If you prefer switch, use a 'default' case and an if condition there like
default:
if(n == -1){
//Your code
}
break;
you can use typeof:
<script>
var t =((typeof "Test")=='string')?true:false;
switch(t){
case false:
alert("t != TEST");
break;
}
</script>
case statement always looks for true. Since you actually want to check if the variable is a string (as I read in the comment in your code), maybe this approach could be right for you:
var t = "TEST";
switch(typeof t){
case "string":
break;
default:
alert("t is not a string");
break;
}
EDIT:
If you have more cases in your real code, maybe the code below would do the job?
var t = "TEST";
switch(t){
case t:
if ("string" != typeof t) {
alert("t is not a string");
break;
}
case "TEST":
alert("case 2");
break;
case "something_else":
alert("case 3");
break;
}
Here's an example fiddle: http://jsfiddle.net/Rz7Sf/. Replace the t variable value with an integer and you should see the proper alert.
Let's say:
var t = "TEST";
switch(t){
case "TEST":
break;
default:
alert("This is the case you want");
break;
}