Determine if string is in list in JavaScript
Solution 1:
EcmaScript 6 and up
If you're using ES6 or higher, the cleanest way is to construct an array of the items and use Array.includes
:
['a', 'b', 'c'].includes('b')
This has some inherent benefits over indexOf
because it can properly test for the presence of NaN
in the list, and can match missing array elements such as the middle one in [1, , 2]
to undefined
. includes
also works on JavaScript typed arrays such as Uint8Array
.
If you're concerned about browser support (such as for IE or Edge), you can check Array.includes
at CanIUse.Com, and if you want to target a browser or browser version that's missing includes
, I recommend polyfill.io for polyfilling.
Higher Performance
Note that Array.includes()
scales in its time with the number of elements in the array: it has performance O(n). If you need higher performance, and won't be constructing the set of items repeatedly (but will be repeatedly checking if the items contain some element), you should use a Set
.
const interestingItems = new Set(['a', 'b', 'c'])
const isItemInSet = interestingItems.has('b')
Note that you can pass in any iterable item to the Set
constructor (anything that supports for...of). You can also convert a Set
to an array using Array.from(set)
.
Without An Array
This is not really recommended, but you could add a new isInList
property to strings as follows:
if (!String.prototype.isInList) {
Object.defineProperty(String.prototype, 'isInList', {
get: () => function(...args) {
let value = this.valueOf();
for (let i = 0, l = args.length; i < l; i += 1) {
if (arguments[i] === value) return true;
}
return false;
}
});
}
Then use it like so:
'fox'.isInList('weasel', 'fox', 'stoat') // true
'fox'.isInList('weasel', 'stoat') // false
You can do the same thing for Number.prototype
.
Note that Object.defineProperty
cannot be used in IE8 and earlier, or very old versions of other browsers. However, it is a far superior solution to String.prototype.isInList = function() { ... }
because using simple assignment like that will create an enumerable property on String.prototype
, which is more likely to break code.
Array.indexOf
If you are using a modern browser, indexOf
always works. However, for IE8 and earlier you'll need a polyfill.
If indexOf
returns -1, the item is not in the list. Be mindful though, that this method will not properly check for NaN
, and while it can match an explicit undefined
, it can’t match a missing element to undefined
as in the array [1, , 2]
.
Polyfill for indexOf
or includes
in IE, or any other browser/version lacking support
If you don't want to use a service like polyfill.io as mentioned above, you can always include in your own source code standards-compliant custom polyfills. For example, Mozilla Developer Network has one for indexOf
.
In this situation where I had to make a solution for Internet Explorer 7, I "rolled my own" simpler version of the indexOf()
function that is not standards-compliant:
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(item) {
var i = this.length;
while (i--) {
if (this[i] === item) return i;
}
return -1;
}
}
Notes On Modifying Object Prototypes
However, I don't think modifying String.prototype
or Array.prototype
is a good strategy long term. Modifying object prototypes in JavaScript can lead to serious bugs. You need to decide whether doing so is safe in your own environment. Of primary note is that iterating an array (when Array.prototype has added properties) with for ... in
will return the new function name as one of the keys:
Array.prototype.blah = function() { console.log('blah'); };
let arr = [1, 2, 3];
for (let x in arr) { console.log(x); }
// Result:
0
1
2
blah // Extra member iterated over!
Your code may work now, but the moment someone in the future adds a third-party JavaScript library or plugin that isn't zealously guarding against inherited keys, everything can break.
The old way to avoid that breakage is, during enumeration, to check each value to see if the object actually has it as a non-inherited property with if (arr.hasOwnProperty(x))
and only then work with that x
.
The new ES6 ways to avoid this extra-key problem are:
-
Use
of
instead ofin
,for (let x of arr)
. However, depending on the output target and the exact settings/capabilities of your down-leveling transpiler, this may not be reliable. Plus, unless you can guarantee that all of your code and third-party libraries strictly stick to this method, then for the purposes of this question you'll probably just want to useincludes
as stated above. -
Define your new properties on the prototype using
Object.defineProperty()
, as this will make the property (by default) non-enumerable. This only truly solves the problem if all the JavaScript libraries or modules you use also do this.
Be Aware of One Last Issue
Last, be aware that while polyfills make sense, and modifying object prototypes is a useful strategy, there can occasionally still be scoping problems with that approach.
In a browser, each distinct document
object is its own new global scope, and in browser JS it is possible to create new documents (such as those used for off-screen rendering or to create document fragments) or to get a reference to another page's document
object (such as via inter-page communication using a named-target link) so it's possible in certain (rare?) circumstances that object prototypes won't have the methods you expect them to have—though you could always run your polyfills again against the new global objects...
In node, modifying prototypes of global
objects may be safe, but modifying the prototypes of non-global, imported objects could lead to breakage if you ever end up with two versions of the same package being required/imported, because imports of the two versions will not expose the same objects, thus won't have the same object prototypes. That is, your code could work fine until a dependency or sub-dependency uses a different version from the one you expect, and without any of your own code changing, a simple npm install
or yarn install
could trigger this problem. (There are options to deal with this, such as yarn's resolutions
property in the package.json
, but that's not a good thing to rely on if you have other options.)
Solution 2:
You can call indexOf
:
if (['a', 'b', 'c'].indexOf(str) >= 0) {
//do something
}
Solution 3:
Most of the answers suggest the Array.prototype.indexOf
method, the only problem is that it will not work on any IE version before IE9.
As an alternative I leave you two more options that will work on all browsers:
if (/Foo|Bar|Baz/.test(str)) {
// ...
}
if (str.match("Foo|Bar|Baz")) {
// ...
}
Solution 4:
Arrays have an indexOf
method which can be used to search for strings:
js> a = ['foo', 'bar', 'baz']
foo,bar,baz
js> a.indexOf('bar')
1
js> a.indexOf('quux')
-1