I have an array of strings, I want to use jQuery to see if a particular string is contained within the array?
Can i do this with jQuery>?
I have an array of strings, I want to use jQuery to see if a particular string is contained within the array?
Can i do this with jQuery>?
You can use $.inArray()
and check that the result is not == -1
, like this:
var arr = [ "string1", "string2" ];
jQuery.inArray("string1", arr) // returns 0
jQuery.inArray("string2", arr) // returns 1
jQuery.inArray("string3", arr) // returns -1
And for the flame wars about "why use jquery?" here...it's because older IE (and maybe current IIRC) doesn't have the Array.indexOf
function, $.indexOf()
will use the built-in Array.indexOf
is it's present, it's just a wrapper to take care of IE not having this.
Alternatively, you can add the Array.indexOf
method if it's not present, bobince shows how to do that here.
var arr = ["foo", "bar"];
if(/\bfoo\b/.test(arr.join('|'))) alert('yay');
I didn't want to start the flamewars
on Nick's answer :p But this plain javascript should do it aswell for OPs requirement.