use string "includes()" in switch Javascript case
Question:
use string “includes()” in switch Javascript case
While the includes()
method will work, it is case sensitive, and just matches any characters. I have found a Regex solution that I like much better, and provides a lot of flexibility. For example, you could easily change this to match only WORDS.
var sourceStr = 'Some Text and literaltextforcase2 and more text'
switch (true) { // sourceStr
case (/LiteralTextForCase1/i.test(sourceStr)):
console.log('Case 1');
break;
case (/LiteralTextForCase2/i.test(sourceStr)):
console.log('Case 2');
break;
default:
console.log('ERROR No Case provided for: ' + sourceStr);
};
//-->Case 2
This will work, but it shouldn't be used in practice.
const databaseObjectID = "someId"; // like "product/217637"
switch(true) {
case databaseObjectID.includes('product'): actionOnProduct(databaseObjectID); break;
case databaseObjectID.includes('user'): actionOnUser(databaseObjectID); break;
// .. a long list of different object types
}
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);
Sorry, I'm a noob so someone will probably have to clean this up, but here is the idea. Pass to a function to check and return a category then use the switch.
function classify(string){
var category = categorize(string);
switch (category) {
case 'product':
console.log('this is a product');
break;
case 'user':
console.log('this is a user');
break;
default:
console.log('category undefined');
}
}
function categorize(string){
if (string.includes('product')){
return 'product';
}
if (string.includes('user')){
return 'user';
}
}
classify("product789");
classify("user123");
classify("test567");
Sorry, as well, for not matching your example.