0

With help of this thread I got the following piece of code, which find all occurrences of words with at least 3 letters:

arr = ["ab", "abcdef", "ab test"]

var AcceptedItems = arr.filter(function(item) {
    return item.match(/[a-zA-Z]{3,}/);
});

In my case that should be abcdef and test.

But instead of the occurrences only, it gets me the whole entry of the array. So instead of just test it gets me ab test.

How can I get only the match (test), not the whole array entry.

Community
  • 1
  • 1
Evgenij Reznik
  • 17,916
  • 39
  • 104
  • 181

1 Answers1

1

.filter will keep an element if it matches the predicate you passed but you need to save a new value based on if that predicate is true. You could do this by first performing a map then a filter but I'd rather do this in one loop.

var AcceptedItems = [];
for (var i = 0, len = arr.length; i < len; i++) {
  var match = arr[i].match(/[a-zA-Z]{3,}/);
  if (match) {
    AcceptedItems.push(match[0]);
  }
}
Mike Cluck
  • 31,869
  • 13
  • 80
  • 91