How can I call a JavaScript function if a string contains any of the items in an array?
Yes, I can use jQuery :)
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();
}
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With