snippetjavascriptCritical
How to find if an array contains a specific string in JavaScript/jQuery?
Viewed 0 times
arrayhowjqueryfindspecificstringjavascriptcontains
Problem
Can someone tell me how to detect if
"specialword" appears in an array? Example:categories: [
"specialword"
"word1"
"word2"
]Solution
You really don't need jQuery for this.
Hint: indexOf returns a number, representing the position where the specified searchvalue occurs for the first time, or -1 if it never
occurs
or
It's worth noting that
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.Code Snippets
var myarr = ["I", "like", "turtles"];
var arraycontainsturtles = (myarr.indexOf("turtles") > -1);function arrayContains(needle, arrhaystack)
{
return (arrhaystack.indexOf(needle) > -1);
}Context
Stack Overflow Q#6116474, score: 1171
Revisions (0)
No revisions yet.