Check if a string contains any element of an array in JavaScript -


how can check if string contains element of array? want filter array if element has string. please see below code.

var arr = ['banana', 'monkey banana', 'apple', 'kiwi', 'orange'];    function checker(value) {    var prohibited = ['banana', 'apple'];      (var = 0; < prohibited.length; i++) {      if (value.indexof(prohibited[i]) == -1) {        return true;      } else {        return false;      }    }  }    arr = arr.filter(checker);  console.log(arr);

the result [ 'apple', 'kiwi', 'orange' ]. 'apple' should removed, isn't.

above code filtered 'banana', not 'apple'. have many keywords filter. there easier way?

problem lies in loop, iterates once since return ends function, cutting off loop in process. so, can update code make function return once loop has been completed .

var arr = ['banana', 'monkey banana', 'apple', 'kiwi', 'orange'];    function checker(value) {    var prohibited = ['banana', 'apple'];      (var = 0; < prohibited.length; i++) {      if (value.indexof(prohibited[i]) > -1) {        return false;      }    }    return true;  }    arr = arr.filter(checker);  console.log(arr);


for reducing function can use every() , indexof() methods

the 'every' method executes provided callback function once each element present in array until finds 1 callback returns falsy value (a value becomes false when converted boolean). if such element found, every method returns false. otherwise, if callback returned true value elements, every return true. callback invoked indexes of array have assigned values; not invoked indexes have been deleted or have never been assigned values.(taken here)

var arr = ['banana', 'monkey banana', 'apple', 'kiwi', 'orange'];    function checker(value) {    var prohibited = ['banana', 'apple'];    return prohibited.every(function(v) {      return value.indexof(v) == -1;    });  }    arr = arr.filter(checker);  console.log(arr);


for older browser check polyfill option of every method.


you use regex here. generate regex using array , use test() check match

var arr = ['banana', 'monkey banana', 'apple', 'kiwi', 'orange'];    function checker(value) {    var prohibited = ['banana', 'apple'];    var regex = new regexp(prohibited.map(function(s) {      return s.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&')    }).join('|'));    return !regex.test(value);  }    arr = arr.filter(checker);  console.log(arr);

refer answer string regex conversion : can create javascript regexes on fly using string variables?


Comments

Popular posts from this blog

scala - 'wrong top statement declaration' when using slick in IntelliJ -

c# - DevExpress.Wpf.Grid.InfiniteGridSizeException was unhandled -

PySide and Qt Properties: Connecting signals from Python to QML -