Reputation: 1655
I have a string and want to check if there is a substring with switch/case. The fnstringCheck returns true
for example if the fnstring is dies_ist_ein_test_diagnosen_erfassen
.
What's going wrong? Thanks for your hints
var fnstring = (interim_transcript).toLowerCase().replace(/ /gi, "_");
console.log('fnstring:', fnstring)
var fnstringCheck = fnstring.indexOf("diagnosen_erfassen") !== -1;
console.log(fnstringCheck)
switch (fnstring) {
case (fnstring.indexOf("_arztbrief_analysieren") !== -1):
$('.analyzesBtn').trigger('click');
break;
case (fnstring.indexOf("_einleitung_erfassen") !== -1):
changeSection('einleitung', mergedSource);
break;
case (fnstring.indexOf("diagnosen_erfassen") !== -1):
changeSection('einleitung', mergedSource);
break;
...
Upvotes: 2
Views: 3723
Reputation: 6325
When you use switch statement, the expression in the switch is evaluated and compared to the values in the cases in order to decide which is the case statement that should be executed. See the documentation here.
In your case, the switch statement has a string expression, but your cases are evaluating to true or false, so none of them matches.
In my opinion, it would look more natural to express your logic with if-else checks:
if (fnstring.indexOf("_arztbrief_analysieren") !== -1) {
$('.analyzesBtn').trigger('click');
} else if (fnstring.indexOf("_einleitung_erfassen") !== -1) {
changeSection('einleitung', mergedSource);
} else if (fnstring.indexOf("diagnosen_erfassen") !== -1) {
changeSection('einleitung', mergedSource);
}
Upvotes: 1
Reputation: 10997
Switch case doesn't work like this. Parameter given to switch is used to compare with each case. In your case switch
took a string param and all case is having boolean properties.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch
Upvotes: -1
Reputation: 386680
You need to take true
in the switch
statement, because the cases returns either true
or false
. The check uses a Identity/strict equality operator ===
.
var fnstring = (interim_transcript).toLowerCase().replace(/ /gi, "_");
console.log('fnstring:', fnstring)
var fnstringCheck = fnstring.indexOf("diagnosen_erfassen") !== -1;
console.log(fnstringCheck)
switch (true) { // strict comparison
case fnstring.indexOf("_arztbrief_analysieren") !== -1:
$('.analyzesBtn').trigger('click');
break;
case fnstring.indexOf("_einleitung_erfassen") !== -1:
changeSection('einleitung', mergedSource);
break;
case fnstring.indexOf("diagnosen_erfassen") !== -1:
changeSection('einleitung', mergedSource);
break;
}
Upvotes: 2