Reputation: 328
I am trying to display a list of items...
Item A Item B Item C Item D
I can tell the code to not display any items that contain A like so:
exclusions = new Array("A")
if (v.value.indexOf(exclusions) > -1) {
}
else {
DO SOMETHING
}
Where I get stuck is if I want it to exclude more than one, like so:
exclusions = new Array("A", "B")
if (v.value.indexOf(exclusions) > -1) {
}
else {
DO SOMETHING
}
Upvotes: 0
Views: 140
Reputation: 120188
One way would be to use a regex.
var matches = "there is a boy".match(/[ab]/);
if (matches === null) {
// neither a nor b was present
}
If you need to construct a regex from strings, you can do it like
var matches = "there is a boy".match(new RegExp("[ab]"));
If you have an array of strings like ['a', 'b']
then you need to do something like
var pattern = yourArray.join('');
var regex = new RexExp(pattern);
here we construct a string which is a pattern, and then create a new regex based on that pattern.
Upvotes: 2
Reputation: 816404
Here is a different way of using indexOf
, utilising Array#every
[MDN]:
var val = v.value;
if(exclusions.every(function(x) { return val.indexOf(x) === -1 })) {
// val does not contain any string in `exclusions`
}
Upvotes: 1
Reputation: 116147
Answering in pseudo - code fashion:
exclusions = new Array("A", "B");
exclusion_found = false;
for (int i=0; i< exclusions.length; i++) {
if (v.value.indexOf(exclusions[i]) > -1) {
exclusion_found = true;
break;
}
}
if (!exclusion_found) {
DO SOMETHING
}
Upvotes: 1