Compare multiple values against the same variable
Use indexOf
with array of values
var valArr = ["kivi","apples","lychee","banana.C","mangos"];
if(valArr.indexOf(val) > -1){
.......
}
You can create an array and check if the value exists in array.
Array#includes
var fruits = ['kivi', 'apples', 'lychee', 'banana.C', 'mangos'];
if (fruits.includes(val)) {
var fruits = ['kivi', 'apples', 'lychee', 'banana.C', 'mangos'];
document.getElementById('test').addEventListener('keyup', function() {
document.getElementById('result').textContent = 'Contains? ' + fruits.includes(this.value);
}, false);
<input type="text" id="test" />
<div id="result"></div>
Note that this is supported in latest browsers. However, polyfill can be used in older browsers.
Browser CompatibilityMDN
Nope. That's about as short as it gets for direct string comparison.
If you have a lot of values to compare against you could put those values in an array and use indexOf
, like this:
var comparisons = ["kivi", "apples", "lychee", "banana.C", "mangos" ];
if (comparisons.indexOf(val) != -1) {
// do something...
}