Check if a string is in an array in jQuery

September 15, 2013 | 762 views | Comments

Use the jQuery function inArray() to find a string in an array, it will check if an array contains a given string and will return the index of the matched string, -1 if no match was found.

For example.

Find the word Dog from a given array.

var theArray = ["The","Quick","Brown","Fox"];
if(jQuery.inArray("Dog",theArray)!==-1){
	console.log("Dog was found...");
}
else{
	console.log("Dog was not found...");
}
//result: Dog was not found...

Find the word Fox from a given array.

var theArray = ["The","Quick","Brown","Fox"];
if(jQuery.inArray("Fox",theArray)!==-1){
	console.log("Fox was found...");
}
else{
	console.log("Fox was not found...");
}
//result: Fox was found...

Note that the search is case sensitive. Therefore, Dog!=dog, or Fox!=fox. What can be done about it? Convert all the values of the given array to lowercase, the string to be search should also contain with all small letters.