Switch statement for string matching in JavaScript
You can't do it in a (This isn't quite true, as Sean points out in the comments. See note at the end.)switch
unless you're doing full string matching; that's doing substring matching.
If you're happy that your regex at the top is stripping away everything that you don't want to compare in your match, you don't need a substring match, and could do:
switch (base_url_string) {
case "xxx.local":
// Blah
break;
case "xxx.dev.yyy.com":
// Blah
break;
}
...but again, that only works if that's the complete string you're matching. It would fail if base_url_string
were, say, "yyy.xxx.local" whereas your current code would match that in the "xxx.local" branch.
Update: Okay, so technically you can use a switch
for substring matching, but I wouldn't recommend it in most situations. Here's how (live example):
function test(str) {
switch (true) {
case /xyz/.test(str):
display("• Matched 'xyz' test");
break;
case /test/.test(str):
display("• Matched 'test' test");
break;
case /ing/.test(str):
display("• Matched 'ing' test");
break;
default:
display("• Didn't match any test");
break;
}
}
That works because of the way JavaScript switch
statements work, in particular two key aspects: First, that the cases are considered in source text order, and second that the selector expressions (the bits after the keyword case
) are expressions that are evaluated as that case is evaluated (not constants as in some other languages). So since our test expression is true
, the first case
expression that results in true
will be the one that gets used.
Switch Case statement for Regex matching in JavaScript
You need to use a different check, not with String#match
, that returns an array or null
which is not usable with strict comparison like in a switch
statement.
You may use RegExp#test
and check with true
:
var regex1 = /a/, regex2 = /b/, regex3 = /c/, samplestring = 'b';
switch (true) { case regex1.test(samplestring): console.log("regex1"); break; case regex2.test(samplestring): console.log("regex2"); break; case regex3.test(samplestring): console.log("regex3"); break;}
use string includes() in switch Javascript case
You usage would be considered an abuse of case.
Instead just use ifs
if (databaseObjectId.includes('product')) actionOnProduct(databaseObjectID);
else if (databaseObjectId.includes('user')) actionOnUser(databaseObjectID);
// .. a long list of different object types
If the ObjectId contains static content around the product or user, you can remove it and use the user or product as a key:
var actions = {
"product":actionOnProduct,
"user" :actionOnUser
}
actions[databaseObjectId.replace(/..../,"")](databaseObjectId);
How to match a template string in switch statement with js?
My guess would be that getId() is returning a different value then what you expect. I would try the following and make that getId() is returning the expected value when it is being calculated
getComponentByPathname = pathname => {
const case3 = `/view3/${getId()}`;
console.log(`case3 = ${case3}`);
console.log(`pathname = ${pathname}`);
switch (pathname) {
case '/view1':
return <ViewOneComponent>;
case '/view2':
return <ViewTwoComponent>;
case case3:
return <ViewThreeComponent>;
}
};
But if you only need to decide which component to render based on your path then something like this might be more appropriate
const examplePaths = ['view1/', 'view2/', 'view3/', 'view3/1241232', 'view3/8721873216', 'view4/', 'vi/ew1', ''];
const mapper = { view1: 'ViewOneComponent', view2: 'ViewTwoComponent', view3: 'ViewThreeComponent'};
examplePaths.forEach(ent => { const splitPaths = ent.split('/');
const mapped = mapper[splitPaths[0]]; if (mapped) { console.log(mapped); } else { console.log('Path not supported'); }});
Switch Case Regex Test
switch-case
doesn't work that way.
regex.test()
method returns a boolean (true/false) and you are comparing that against the input string itself which will not be true for any of the case
statement.
You need to convert switch-case
into multiple if / else if / else
block to execute your logic.
Why does my Switch-statement case not fire on exact string matches?
For a "work-around" you can try with this mapping function:
// Return correct uni name.
function doUniMapping(uni) {
uni = uni.trim();
return uniMapping.hasOwnProperty(uni) ?
uniMapping[uni]: `University ${uni} not matches.`;
}
console.log(doUniMapping(subUniName));
Here the mapping object:
const uniMapping = {
"Hochschule Fresenius (Wiesbaden)":
"Hochschule Fresenius University of Applied Sciences",
'Hochschule RheinMain (Wiesbaden und Rüsselsheim)':
"Hochschule RheinMain University of Applied Sciences Wiesbaden Rüsselsheim",
'EBS Universität für Wirtschaft und Recht (Wiesbaden, Oestrich-Winkel)':
"EBS Universität für Wirtschaft und Recht",
'Hochschule Ruhr West (Mülheim, Bottrop)':
"Hochschule Ruhr West University of Applied Sciences",
"Duale Hochschule Baden-Württemberg (Stuttgart)":
"DHBW - Duale Hochschule Baden-Württemberg",
'Hochschule Augsburg (HSA)':
"Hochschule für angewandte Wissenschaften Augsburg - University of Applied Sciences",
'Hochschule Karlsruhe - Technik und Wirtschaft':
"Hochschule Karlsruhe - Technik und Wirtschaft - University of Applied Sciences",
'Hochschule Westküste (Heide)':
""
};
Here a full working example with a mapping object:
https://stackblitz.com/edit/js-matching-uni-mapping?file=index.js
I think is better of your switch.
Next time in the question, insert a piece of code with your problem, with stackblitz or whatever you prefer.
I can't extract the output strings from your screenshot so you'll have to try it out yourself.
EDIT: There's a strange space character: ' ' between string name and '('.
Here a modified working example from your code, using replace
:
https://stackblitz.com/edit/js-matching-uni-db-strings?file=index.js
I suggest you to remove that character from your DB records.
EDIT2: The next time you can find these strange character with a text editor like Notepad++, in this way:
Switch combining cases string regex and number
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)
Related Topics
Prevent Automatic Browser Scroll on Refresh
How JavaScript Closures Are Garbage Collected
Why Is Bind Slower Than a Closure
How to Skip Over an Element in .Map()
Contain Form Within a Bootstrap Popover
How to Join Two JavaScript Objects, Without Using Jquery
Unique Object Identifier in JavaScript
Changing the Default Title of Confirm() in JavaScript
How to Filter by Object Property in Angularjs
How to Make 'Setinterval' Behave More in Sync, or How to Use 'Settimeout' Instead
How to Create a Hash or Dictionary Object in JavaScript
Is 'Window' Really Global in JavaScript
Settimeout/Cleartimeout Problems
JavaScript Getelementbyid Based on a Partial String
Script438: Object Doesn't Support Property or Method Ie
Map Isn't Showing on Google Maps JavaScript API V3 When Nested in a Div Tag