Function call if the string contains any elements in the array

How can I call a JavaScript function if a string contains any element in an array?

Yes, I can use jQuery :)

+3
source share
3 answers

You can use some () , the Mozilla extension that was added in ECMAScript 5:

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

You can 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();
}
+2
source

Just loop the elements in the array and find the value. This is what you need to do anyway, even if you use some kind of method for this. By looping yourself, you can easily get out of the loop as soon as you find a match that on average reduces the number of items you need to check in half.

for (var i=0; i<theArray.length; i++) {
  if (theArray[i] == theString) {
    theFunction();
    break;
  }
}
+1
source

Source: https://habr.com/ru/post/1729671/


All Articles