Reputation: 251
This is my example
if(someString == 'string1' || someString == 'string2' || someString == 'string3' || someString == 'string4');
Is there any trick to using shorter syntax?
Upvotes: 0
Views: 67
Reputation: 1
ES6 includes will do it
const options = ['string1','string2','string3'];
if (options.includes(someString)) {
// do something
}
Upvotes: 0
Reputation: 16224
You can use include and add all the possibilities into an array:
var matches = ['string1', 'string2', 'string3', 'string4'];
var something = 'string2';
var isInArray = matches.includes(something);
console.log(isInArray); // true
Upvotes: 0
Reputation: 2537
Create a pre-defined Set of the values you want to check, and use the .has()
method to test for it:
var vals = new Set(['string1', 'string2', 'string3', 'string4']);
var someString = "string2";
var otherString = "stringX";
console.log(vals.has(someString)); // true
console.log(vals.has(otherString)); // false
So with an if
statement, it would look like this:
if (vals.has(someString)) {
// your code
}
Upvotes: 1
Reputation:
switch (someString) {
case "string1":
case "string2":
case "string3":
case "string4":
// do something
break;
default:
// this would the else
}
Upvotes: 0
Reputation: 292
there is nothing like if(string == "str1" || "str2" || ..., at least not in the languages i know, and it actually makes sense there isn't, because everything is a logical expression. if you have a large number of comparisons, you can do something like
strings = ["str1", "str2", "str3", ...];
var match = false;
for(var i = 0; i < string.length; i++){
if(strings[i] == someString){ match = true; break; }
}
if(match){ ... do something }
if you only have primitive objects and non-complex comparisons (just finding something), you can use string / array methods as well
Upvotes: 0
Reputation: 42304
You could always put the possible values into an array, and then check whether the string matches any of the values in the array:
var someString = 'string2';
var possibleValues = ["string1", "string2", "string3", "string4"];
if (possibleValues.indexOf(someString) > -1) {
console.log('Matched at index: ' + possibleValues.indexOf(someString));
}
Upvotes: 1