views:

144

answers:

3

How can i call a javascript function if a string contains any of the items in an array()?

Yes, i can use jquery :)

+2  A: 

You could use the grep function to find if there are any elements that satisfy the condition:

// get all elements that satisfy the condition
var elements = $.grep(someArray, function(el, index) {
    // This assumes that you have an array of strings
    // Test if someString contains the current element of the array
    return someString.indexOf(el) > -1;
});

if (elements.length > 0) {
    callSomeFunction();
}
Darin Dimitrov
+1  A: 

Simply loop over the items in the array and look for the value. That's what you have to do anyway even if you use some method to do it for you. By looping yourself you can easily break out of the loop as soon as you find a match, that will by average cut the number of items you need to check in half.

for (var i=0; i<theArray.length; i++) {
  if (theArray[i] == theString) {
    theFunction();
    break;
  }
}
Guffa
don't use `for..in` to loop over arrays!
Christoph
@Christoph: Thanks for the heads up. I don't usually use for..in, and it's used in tutorials without any note of any possible risks.
Guffa
@Guffa: there's a lot of bad JS code around; that's the problem with popular languages: everyone claims to 'know' them and feels inclined to spread their knowledge; even information coming from 'official' sources where you'd think the guys should know what they are talking about is sometimes just plain wrong (*cough* Apple JavaScript Coding Guidelines)
Christoph
+1  A: 

You could use some(), a Mozilla extension which has been added to ECMAScript 5:

var haystack = 'I like eggs!';
if(['spam', 'eggs'].some(function(needle) {
    return haystack.indexOf(needle) >= 0;
})) alert('spam or eggs');
Christoph