Friday 5 August 2016

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




Can someone tell me how to detect if "specialword" appears in an array? Example:




categories: [
"specialword"
"word1"
"word2"
]

Answer



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.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...