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
Related
I have this code -
const myFunc = () => {
switch (transcript) {
case transcript.split(" ").includes("hello"):
case transcript.split(" ").includes("hey"):
case "hi":
case "hallo":
const greetingArray = ["Hello!", "Hi!"];
const randomItem =
greetingArray[Math.floor(Math.random() * greetingArray.length)];
setMyVar(randomItem);
TTS(myVar, "english");
break;
case "bye":
TTS("Goodbye", "english");
break;
}
return myVar;
};
As you can see, I tried to check if the words hey and hello is there in the transcript, but it isn't working.
How can I correct this?
Thanks in advance!!
.includes returns true/false so it would look like case true: case: false which is pointless code. It compiles (pseudo code) to something weird like this:
val = "hello";
if (val: string == (val.split(" ").includes("hello"): boolean) || val == "hi" || etc) {
... do set var stuff
}
case "word": does work, however it would mean the transcript can ONLY and must be character by character identical to the "word".
So the includes do nothing, and because the following case's say "hallo" and "hi", hello/hey will not trigger any case and because theirs no default event it just escapes.
Your fix would be changing both your transcript.split.includes to simply "hello" and "hey".
//This is my Problem
Complete the getLetter(s) function in the editor. It has one parameter: a string, , consisting of lowercase English alphabetic letters (i.e., a through z). It must return A, B, C, or D depending on the following criteria:
If the first character in string is in the set {aeiou}, then return A.
If the first character in string is in the set {bcdfg}, then return B.
If the first character in string is in the set {hjklm},, then return C.
If the first character in string is in the set {npqrstvwxyz}, then return D.
I am trying to implement the above scenarion and to dthis I have written the following code.
//Here is my code
function getLetter(s) {
let letter;
// Write your code here
switch (s) {
case s.match(/[aeiou]/g).includes(s[0]):
letter = 'A'
break;
case s.match(/[bcdfg]/g).includes(s[0]):
letter = 'B'
break;
case s.match(/[hjklm]/g).includes(s[0]):
letter = 'C';
break;
case s.match(/[npqrstvwxyz]/g).includes(s[0]):
letter = 'D';
break;
default:
console.log("hello")
}
return letter
}
The code is showing error. Would any help me to figure it out? How can I implement the above task using switch statement.
I don't know that much switch case, but maybe you can use parenthesis for the switch statement and if "s.match(/[aeiou]/g).includes(s[0])" return true or false
And you forgot ";" after the two first assignment
the way you wrote the switch case may be partially correct in GoLang. but in Javascript, it is not possible to achieve this using Switch-Case statement.
Better try using if-else-if statement something like below
if(s.test(/^[aeiou]/)) {
return 'A';
} else if(s.test(/^[bcdfg]/)) {
return 'B'
}
Check out this: Switch statement for string matching in JavaScript. The issue is that match returns null, which breaks the switch statement.
Use
switch(s){
case str.match(/^xyz/)?.input:
//code
break;
This stops the match from returning null.
Based on how you're using this, you actually want to switch (true) and not switch (s)
i.e. when you have a case y in a switch (x), the test being done is x === y; so you want to do true === some.test()
const s = 'a';
switch (true) {
case /a/.test(s):
console.log('first match');
break;
case /b/.test(s):
console.log('second match');
break;
default:
console.log('no match');
break;
}
Will log first match because
/a/.test('a') is true
and true /* from switch */ === true /* from case test */
Note that in most cases switch can also be written as if..else if..else.
Base your decision on which to use by which is the most readable (err on the side of if patterns)
The above example written as an if might look like this
const s = 'a';
if (/a/.test(s)) {
console.log('first match');
} else if (/b/.test(s)) {
console.log('second match');
} else {
console.log('no match');
}
This question already has answers here:
javascript switch(true)
(5 answers)
Closed 5 years ago.
Good afternoon!
Why does the first option work - switch (true), and the second option does not work - switch (a)?
First:
var a= prompt('Enter value', '');
switch(true)
{
case a>10:
alert('a>10');
break;
case a<10:
alert('a<10');
break;
default:
alert('a===10');
Second:
var a= prompt('Enter value', '');
switch(a)
{
case a>10:
alert('a>10');
break;
case a<10:
alert('a<10');
break;
default:
alert('a===10');
Why does the first option work - switch (true), and the second option
does not work - switch (a)?
As per documentation
The switch statement evaluates an expression, matching the
expression's value to a case clause, and executes statements
associated with that case.
So, in your first option true will match to either a < 10 or a > 10, however in second option, a being a string may not match to either of them.
Edit: I just realize OP ask for the difference instead of why it won't work, sorry for misunderstanding the question
It should work nicely
var a = prompt('Enter value', '');
switch (true) {
case (a > 10):
alert("a > 10");
break;
case (a < 10):
alert("a < 10");
break;
default:
alert('a == 10');
}
It's because a > 10 is true, like the switch(true), while switch(a) was passed a, which is not true. Of course, you should cast a. a = +a or use parseInt() or parseFloat().
Here's what you probably meant to do:
var a = prompt('Enter value');
if(+a > 10){
alert('a > 10');
}
else if(a !== '' && +a < 10){
alert('a < 10');
}
else if(+a === 10){
alert('a === 10');
}
else{
alert('Really, you should avoid using prompt and alert!');
}
// notice this is less code than that pointless switch
You need to convert the user input from a string to an integer, like so
a = parseInt(a)
I have the following switch block:
var str = 'matches[pw1]';
switch (str)
{
case (str.indexOf('matches') > -1) :
console.log('yes');
break;
default:
console.log(str.indexOf('matches') ) ;
console.log('no');
break;
}
What I want is, that if str contains the word 'matches', then it should run the first case block, otherwise the default block.
However when I run this, the output I get is '0', and then 'no', meaning the default block is running despite the conditions for the first case being met.
Any ideas what's wrong?
Your case is likely testing whether (str.indexOf('matches') > -1) == str.
EDIT:
It might be valuable to understand exactly what switch and case mean. One of Javascript's ancestors, C, commonly used switch to replace blocks of code where a primitive was being compared against a list of values (often from an enumeration, or a series of literals). So instead of:
if (type == ENABLE_FRAMISTAN)
{
enable_framistan();
}
else if (type == ENABLE_FROBSOSTICATOR)
{
enable_frobnosticator();
}
else if (type == DISABLE_BAZTICULATOR)
{
disable_bazticulator();
}
else
{
assert(false);
}
you could instead write:
switch (type)
{
case ENABLE_FRAMISTAN: enable_framistan(); break;
case ENABLE_FROBNOSTICATOR: enable_frobnosticator(); break;
case DISABLE_BAZTICULATOR: disable_bazticulator(); break;
default: assert(false); break;
}
...which might make it easier to digest (and or spot errors in) a large block of code which effectively mapped type values to functions being called (or some such). Your designated usage, checking to see whether a string matches any of a number of potential (exclusive with one another?) patterns, does not map as well to switch. If it were merely equality being tested, it would work well, but your condition is more sophisticated than switch was designed to express. Any way that you manage to preserve switch with your feature set will likely require less-than-obvious code.
Why not use an if statment? try something like this:
var str = 'matches[pw1]';
if(str.indexOf('matches') > -1) {
console.log('yes');
break;
}else{
console.log(str.indexOf('matches') ) ;
console.log('no');
break;
}
It should work since you don't have alot of cases anyways. I don't think you can do a comparing in cases.
What I want is, that if str contains the word 'matches', then it should run the first case block, otherwise the default block.
You cannot do that with a switch statement. A switch statement compares the result of evaluating the switch expression (in this case str) with the values of the case labels. The case labels can be expressions (as in your example), but if they are the expressions are evaluated and then compared against the value above using ===. (That's what the ECMAScript 5.1 spec says ...)
So what your code is actually doing for that case is (roughly speaking):
evaluate (str.indexOf('matches') > -1) which gives you true or false
compare true or false with the value of str ... which fails and the case body isn't executed.
Now I think you could make your approach work as follows:
case (str.indexOf('matches') > -1 ? str : '') :
console.log('yes');
break;
but that stinks from a code readability perspective (IMO).
You could do this:
console.log( str.indexOf( 'matches' ) > -1 ? 'yes' : 'no' );
You should know the basic usage of switch. I think you mistakenly use Switch. Try to use it as following:
var str = 'matches[pw1]';
str = str.indexOf('matches');
switch (str)
{
case -1 :
console.log('yes');
break;
default:
console.log(str.indexOf('matches') ) ;
console.log('no');
break;
}
Please look at the Following URL http://www.w3schools.com/js/js_switch.asp
If the above is not suitable for your logic, use if.. else if ...
http://www.w3schools.com/js/js_if_else.asp
So lets say I had this switch:
switch(str){
case "something": //a defined value
// ...
break;
case /#[a-zA-Z]{1,}/ //Matches "#" followed by a letter
}
I'm almost sure that the above is almost impossible...but what would be the best way to achieve something similar? Maybe just plain if..else..ifs? That'd be boring...
So how would you achieve this?
You can get the matches for various patterns before you begin the switch,
and set the cases to the index of the match.
(Other conditionals would be easier to read, if not more efficient.)
//var str= 'something';
var str='#somethingelse';
var M= /^(something)|(#[a-zA-Z]+)$/.exec(str);
if(M){
switch(M[0]){
case M[1]:
// ...
alert(M[1]);
break;
case M[2]:
//...
alert(M[2])
break;
}
}
You can use a single regexp. It is not necessarily less boring but it gets the job done.
var result = /(something)|(#[a-zA-Z]{1,})/.exec(str);
if (!result) {
// Handle error?
} else if (result[1]) {
// something
} else if (result[2]) {
// #[a-zA-Z]{1,}
}