【问题标题】:Getting only the match, instead of whole entry仅获取匹配项,而不是整个条目
【发布时间】:2016-02-17 23:43:05
【问题描述】:

this thread 的帮助下,我得到了以下代码,它可以找到所有出现的至少三个字母的单词:

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

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

在我的情况下应该是abcdeftest

但是,它不仅仅是出现,而是让我获得了数组的整个条目。所以不仅仅是test,它让我得到ab test

我怎样才能只得到匹配项 (test),而不是整个数组条目。

【问题讨论】:

  • arr.map(item.match....[0]).filter(Boolean)

标签: javascript arrays regex


【解决方案1】:

.filter 将保留一个元素,如果它与您传递的谓词匹配,但您需要根据该谓词是否为真保存一个新值。您可以先执行 map 然后执行 filter 来做到这一点,但我宁愿在一个循环中执行此操作。

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

【讨论】:

    猜你喜欢
    • 2015-11-23
    • 1970-01-01
    • 2019-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-10
    • 2019-11-27
    相关资源
    最近更新 更多