Evgenij Reznik
Evgenij Reznik

Reputation: 18594

Getting only the match, instead of whole entry

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.

Upvotes: 0

Views: 30

Answers (1)

Mike Cluck
Mike Cluck

Reputation: 32511

.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]);
  }
}

Upvotes: 1

Related Questions