Switch case match with string - javascript

function getFieldType(value){
var type = "";
switch(value){
case "TEXT_BOX":
type=FieldTypeEnum.TEXT_BOX;
break;
case "PASSWORD":
type=FieldTypeEnum.PASSWORD;
break;
case "CHECK_BOX":
type=FieldTypeEnum.CHECK_BOX;
break;
case "RADIO_BUTTON":
type=FieldTypeEnum.RADIO_BUTTON;
break;
case "DROP_DOWN":
type=FieldTypeEnum.DROP_DOWN;
break;
case "SEARCH_CARD_BOX":
type=FieldTypeEnum.SEARCH_CARD_BOX;
break;
case "STATE_DROP_DOWN":
type=FieldTypeEnum.STATE_DROP_DOWN;
break;
case "ID_DROP_DOWN":
type=FieldTypeEnum.ID_DROP_DOWN;
break;
case "GENDER_DROP_DOWN":
type = FieldTypeEnum.GENDER_DROP_DOWN;
break;
default:
type = "";
}
return type;
}
I want to combined three drop down box (STATE_DROP_DOWN, ID_DROP_DOWN, GENDER_DROP_DOWN)into one .
Means I want something like below :
case String.endwith("_DROP_DOWN"):
type=FieldTypeEnum.ID_DROP_DOWN;
break;
Is it possible in JavaScript? If yes then how?

It is possible, in a javascript switch/case statement you can compare for string equality (which evaluates to true or false) or more complex statements which just as when testing for string equality, also evaluate to true or false (e.g. String.endwith("_DROP_DOWN")). However personally I would prefer the following:
STATE_DROP_DOWN:
// intentional fall through
ID_DROP_DOWN:
// intentional fall through
GENDER_DROP_DOWN:
//.. do your stuff
break;
I believe this way it is more clearly through which switch case you are falling in a certain situation.

You can put a ternary operator in the case, and test if it ends with "DROP_DOWN" return value otherwise blank string.
switch(value){
case value.endsWith("_DROP_DOWN") ? value : '' {
type=FieldTypeEnum.ID_DROP_DOWN;
break;
}
}

Related

Why "≠" is converted to "≠", "≥" to "≥", "≤" to "≤" in browsers developers tool(javascript)?

I am working on Javascript/angularjs. From UI, i get symbols as below:
'>' Greater Than
'<' Less Than
'=' Equal
'≠' Not Equal
'≥' Greater Than or Equal to
'≤' Less Than or Equal to
I am using switch case on received symbol
switch (operand) {
case '>':
value = blabla1; break;
case '<':
value = blabla2; break;
case '=':
value = blabla3; break;
case '≠':
value = blabla4; break;
case '≥':
value = blabla5; break;
case '≤':
value = blabla6; break;
default:
value = xyz;
}
My issue is the above gets converted to below in browser("≠" is converted to "≠", "≥" to "≥", "≤" to "≤" ). From which I am not able to do calculations.
switch (operand) {
case '>':
value = blabla1; break;
case '<':
value = blabla2; break;
case '=':
value = blabla3; break;
case '≠':
value = blabla4; break;
case '≥':
value = blabla5; break;
case '≤':
value = blabla6; break;
default:
value = xyz;
}
Can somebody tell me why this is happening? I have used charset="utf-8" in html. Also i tried in online to change the above symbols to encode and decode but none of them resulted in the exact symbol.
Thanks in advance.
Make sure your browser is also using UTF-8 encoding.
Here's a link that will help you check and change your browser's encoding.

Switch combining cases string regex and number

Is there a way to create multiple cases in a single Javascript switch statement?
In my code I receive the value of a field via jQuery.
Is it possible that one case checks for string regex and another for number of the same variable?
I am thinking along the lines of:
var field = $(this).val();
var msg;
switch (field)
{
case field.test('Yes'):
msg = "FOO\n";
break;
case 10:
msg = "BAR\n";
break;
}
Although I saw here: Switch statement for string matching in JavaScript
That the way to use switch on strings is by sending the switch statement a "true" value.
What would be the most concise (and correct!) way to achieve this?
OK, compiling both answers above my code that worked and was most elegant IMO is:
var fieldVal = $(this).val();
var msg;
switch (true)
{
case /Yes/.test(fieldVal):
msg = "FOO";
break;
case fieldVal > 10 :
msg = "BAR";
break;
}
this works as separate if statements since we are evaluating whether or not the case returns true but in a clearer and more concise way that could give us the option to add totally disparate test statements in one switch.
the reason it works is probably that the case expression evaluated is interpreted as a true or false value and then checked against the main -
switch(true)
You can't the case need to single value, that's compared to switch expression, but you can put multiple cases to execute the same code:
switch (field) {
case 'Yes':
case 'yes':
case 'YES':
msg = "FOO\n";
break;
case 10:
msg = "BAR\n";
break;
}
but in order to use test as case you can pass true to switch (I found that trick in some open source project):
switch (true) {
case field.test('Yes'):
msg = "FOO\n";
break;
case field == 10:
msg = "BAR\n";
break;
}
but this is the same as if/else
Note: you're using test() incorrectly, it's a method of a regex object, so you need /Yes/.test(field) rather than field.test('Yes'). Anyway...
If you've only got two cases as shown then I'd use an if/else/else if structure:
var field = $(this).val();
var msg;
if(/Yes/.test(field)) {
msg = "FOO\n";
} else if (field === 10) {
msg = "BAR\n";
}
If you need to add additional cases I'd just add extra if else {} branches on the end.
If you have several specific numeric cases you might consider putting them in a switch with the regex tests in a default at the end:
switch (field) {
case 10:
msg = "BAR\n";
break;
case 30:
msg = "whatever\n";
break;
case 50:
msg = "hi\n";
break;
default:
if (/Yes/.test(field)) {
msg = "FOO\n";
else if (/No|N|False|/i.test(field)) {
msg = "blah\n";
}
break;
}
The switch (true) option you alluded to in the question is really just a messier version of an if/else/else if, so it doesn't really make sense unless you have some fall-through cases:
switch(true)
case /Yes/.test(field):
case /Y/.text(field):
case /Whatever/.text(field):
msg = "FOO\n";
break;
case field == 10:
msg = "BAR\n";
break;
}
...and even then an if with multiple conditions joined by || arguably just as tidy with appropriate newlines, and combining multiple regexes into a single one is probably a lot neater.

How do you have a NaN case in a switch statement?

Since NaN === NaN evaluates to false, is it possible to add a NaN case to a switch statement?
For example, let's say I want to make the following switch:
switch(x){
case 1:
case 2:
case 4:
doSomething();
break;
case NaN:
doSomethingElse();
break;
case default:
doADifferentThing();
break;
}
Sending NaN as x will go to the default case. I know there are ways around using NaN in switch statements (e.g. I can surround with an if..else statement and use isNaN), but is there a more direct approach?
I originally wrote i saw only one solution, however during my sleep i came up with a superb solution.
Always keep in mind that a switch does not do implicit type conversion to compare the cases so if you provide a string to the switch statement it will not match to integers in the cases, and vice versa.
If you want to compare to strings and integers you will have to cast your integer to a string first and then compare to strings only.
The superb solution:
As pointed out by WouterH, my initial solution will resolve to default when using a string that contains a number, this is expected behavior for switch statements. But it might be useful to parse the argument in order to overcome this. For that you can use following code:
var x = "1";
switch (isNaN(x) || parseInt(x))
{
case true:
alert("IsNaN!")
break;
case 1:
alert("1");
break;
case 2:
alert("2");
break;
case 4:
alert("4");
break;
default:
alert("default");
break;
}
My initial superb method :
var x = "clearly not a number";
switch(x){
case !isNaN(x) || x:
alert("IsNaN!")
break;
case 1:
alert("1");
break;
case 2:
alert("2");
break;
case 4:
alert("4");
break;
default:
alert("default");
break;
}
isNaN will return true if x where to be a string but it doesn't really matter because true won't evaluate as true to a string because of the above mentioned behavior of the switch statement.
My original solution:
I don't even know what i was thinking, this looks horrible and the indentation is just plain awkward, but thanks for the upvotes !
var x = "clearly not a number";
switch(x){
case 1:
alert("1");
break;
case 2:
alert("2");
break;
case 4:
alert("4");
break;
case default:
if (isNaN(x)){
alert("isNaN");
break;
}
alert("default");
break;
}
Brad's solution:
thx to Brad for this one.
I don't really like this because it feels a bit like a hack, that is to say, this isn't how you would expect usage of a case statement, but it does give you the most flexibility, so i'm certain there is a use case for it.
var x = "clearly not a number";
switch(true)
{
case x==1:
alert("1");
break;
case x==2:
alert("2");
break;
case IsNaN(x):
alert("IsNaN");
break;
case default:
alert("default");
break;
}
You could do this (jsFiddle):
var x = "test";
switch (isNaN(x) || x)
{
case true:
alert("IsNaN!")
break;
case 1:
alert("1");
break;
case 2:
alert("2");
break;
case 4:
alert("4");
break;
default:
alert("default");
break;
}
Or if you also want to validate string containing a number (jsFiddle):
var x = "1";
switch (isNaN(x) || parseInt(x))
{
case true:
alert("IsNaN!")
break;
case 1:
alert("1");
break;
case 2:
alert("2");
break;
case 4:
alert("4");
break;
default:
alert("default");
break;
}
#helmus's answer is correct and is a good solution.
However, you can maintain the NaN case if you use strings:
switch(x+''){
case "1":
case "2":
case "4":
doSomething();
break;
case "NaN":
doSomethingElse();
break;
default:
doADifferentThing();
break;
}
use toString():
switch (x.toString()) {
case '1':
case '2':
case '4':
console.log('1/2/4');
break;
case 'NaN':
console.log('NaN');
break;
default:
console.log('default');
}

Switch case - else condition

<script type="text/javascript">
//You will receive a different greeting based
//on what day it is. Note that Sunday=0,
//Monday=1, Tuesday=2, etc.
var d = new Date();
var theDay = d.getDay();
switch (theDay)
{
case 5:
document.write("Finally Friday");
break;
case 6:
document.write("Super Saturday");
break;
case 0:
document.write("Sleepy Sunday");
break;
default:
document.write("I'm looking forward to this weekend!");
}
</script>
If the theDay = 5, then we display Finally Friday. I want if theDay !=5, then display 'Finally Something'.. similarly for others too...
Is it possible without an If/else condition. If the case 5 does not execute, can i do something else in that place?
Is it possible without an If/else condition. If the case 5 does not execute, can i do something else in that place?
No.
The switch statement will execute the first matching case, and then keep going (ignoring all further case labels) until it gets to either a break statement or the end of the switch block - but even though you can "fall through" to subsequent cases by omitting the break statement the switch does not provide any mechanism to say "do something when this case isn't matched/executed, but also keep trying to look for a matching case".
What you are describing would normally be done with a series of if/else statements:
var d = new Date(),
theDay=d.getDay(),
matched = false;
if (theDay === 5) {
matched = true;
document.write("Finally Friday");
} else {
// your != 5 case here
}
if (theDay === 6) {
matched = true;
document.write("Super Saturday");
} else {
// your != 6 case here
}
if (theDay === 0) {
matched = true;
document.write("Sleepy Sunday");
} else {
// your != 0 case here
}
// default when none matched:
if (!matched) {
document.write("I'm looking forward to this weekend!");
}
Note that I've added a matched flag to allow the default to work. And note that there are no else if statements because you need every if/else pair to execute.
If you are really determined to use a switch statement you could do something silly like the following:
var d = new Date(),
theDay = d.getDay(),
c,
cases = { // pre-list all the "not" cases
"!5" : true,
"!6" : true,
"!0" : true
};
// add case for theDay and remove the "not" case for theDay (if there is one)
cases[theDay] = true;
if (cases["!" + theDay])
delete cases["!" + theDay];
for (c in cases) {
switch(c) {
case "5":
document.write("Finally Friday");
break;
case "!5":
document.write("Finally Something");
break;
case "6":
document.write("Super Saturday");
break;
case "!6":
document.write("Finally Something - but not 6");
break;
case "0":
document.write("Sleepy Sunday");
break;
case "!0":
document.write("Finally Something - but not 0");
break;
default:
document.write("I'm looking forward to this weekend!");
}
}
If you need the cases to execute in a specific order use an array rather than an object.
Its like switch does a jump to the matching case, if it doesn't match it will jump to what matches. The answer to your question "If the case 5 does not execute, can i do something else in that place?" is No, because it never reaches that case at all. It jumps to the next matching case or default.
Is it possible without an If/else condition. If the case 5 does not execute, can i do something else in that place?
Use a default code block as seen below. Anything that doesn't match the cases will fallback to the default one.
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
How this works:
The value of the expression is compared with the values of each case.
If there is a match, the associated block of code is executed.
If there is no match, the default code block is executed.
A standard if/else would be the best way to achieve this. I wonder why you want to do it without.
That said, It's not very elegant, but you could try adding the following to the top of your switch statement:
case 0:
case 1:
case 2:
case 3:
case 4:
case 6:
document.write("Finally Something");
Giving you:
switch (theDay)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 6:
document.write("Finally Something");
case 5:
document.write("Finally Friday");
break;
case 6:
document.write("Super Saturday");
break;
case 0:
document.write("Sleepy Sunday");
break;
default:
document.write("I'm looking forward to this weekend!");
}
You can do something like:
var something = 0;
switch (theDay) {
case 5:
document.write("Finally Friday");
something = 15;
break;
case 6:
document.write("Super Saturday");
something = 16;
break;
case 0:
document.write("Sleepy Sunday");
something = 20;
break;
default:
document.write("I'm looking forward to this weekend!");
}
switch (something) {
case 15: document.write("Not Friday"); break;
case 16: document.write("Not Saturday"); break;
case 20: document.write("Not Sunday"); break;
default: document.write("Nothing"); break;
}
Overly complicated answers.
Simplify.
var switchElse = true;
switch (CHECK_SOMETHING)
{
case "SOME_VALUE":
...DO SOMETHING...
switchElse = false;
break;
default:
}
if (switchElse)
{
...DO ELSE...
}
The only solution that can be formulated without a compare.
USE "DEFAULT" PATTERN
var myValue = "Friday"
switch (CHECK_SOMETHING)
{
case "SOME_VALUE":
myValue = "Some Other Day";
default:
}

Why does this switch statement fail?

switch (t.value) {
case < 5:
alert('hi');
break;
}
I know it's the part where I have "< 5". How do I make it so that it has a case where t.value is less than 5??
switch only supports equality comparisons.
if (t.value < 5) {
alert('hi');
}
I don't know if it fits your particular case, but you could also do something like this:
switch (t.value) {
case 5:
case 4:
case 3:
case 2:
case 1:
alert('hi');
break;
}
An if statement seems best suited for this purpose, but although I do not recommend it the fact that JavaScript will let you switch on any datatype (and not just numbers/enums like some languages) means you can do this:
switch(true) {
case t.value < 5:
// do something
break;
case t.value >= 112:
// do something
break;
case someOtherVar == 17:
// do something
break;
case x == 7:
case y == "something":
case z == -12:
case a == b * c:
// works with fallthrough
break;
case someFunc():
// even works on a function call (someFunc() should return true/false)
break;
default:
// whatever
break;
}
The above should select whichever case matches first, noting that several if not all of the cases could be true.
In a way that style is more readable than a long series of if/else if, but I wouldn't use it in a team development environment where it could confuse other developers.
Another, more conventional use of switch for your less than 5 scenario would be as follows (assuming you know the range that t.value could possibly be):
switch(t.value) {
case 0:
case 1:
case 2:
case 3:
case 4:
// do something
break;
case 5:
// etc
}
switch statements don't support less-than or greater-than comparisons (or anything other than equals). Use:
if (t.value < 5) {
alert("hi");
}
default:
if(t.value< 5)
alert('hi');
break;
Maybe it's you want!

Categories

Resources