How to find if an array contains a specific string in JavaScript/jQuery? [duplicate] How to find if an array contains a specific string in JavaScript/jQuery? [duplicate] arrays arrays

How to find if an array contains a specific string in JavaScript/jQuery? [duplicate]


You really don't need jQuery for this.

var myarr = ["I", "like", "turtles"];var arraycontainsturtles = (myarr.indexOf("turtles") > -1);

Hint: indexOf returns a number, representing the position where the specified searchvalue occurs for the first time, or -1 if it never occurs

or

function arrayContains(needle, arrhaystack){    return (arrhaystack.indexOf(needle) > -1);}

It's worth noting that array.indexOf(..) is not supported in IE < 9, but jQuery's indexOf(...) function will work even for those older versions.


jQuery offers $.inArray:

Note that inArray returns the index of the element found, so 0 indicates the element is the first in the array. -1 indicates the element was not found.