Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a function if a string contains any items in an array

How can I call a JavaScript function if a string contains any of the items in an array?

Yes, I can use jQuery :)

like image 839
tarnfeld Avatar asked Jun 11 '26 02:06

tarnfeld


2 Answers

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();
}
like image 119
Darin Dimitrov Avatar answered Jun 13 '26 16:06

Darin Dimitrov


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');
like image 41
Christoph Avatar answered Jun 13 '26 16:06

Christoph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!