How to check if a string array contains one string in JavaScript?

gtludwig picture gtludwig · Sep 27, 2012 · Viewed 469.8k times · Source

I have a string array and one string. I'd like to test this string against the array values and apply a condition the result - if the array contains the string do "A", else do "B".

How can I do that?

Answer

James Allardice picture James Allardice · Sep 27, 2012

There is an indexOf method that all arrays have (except Internet Explorer 8 and below) that will return the index of an element in the array, or -1 if it's not in the array:

if (yourArray.indexOf("someString") > -1) {
    //In the array!
} else {
    //Not in the array
}

If you need to support old IE browsers, you can polyfill this method using the code in the MDN article.