使用正则表达式将字符串与数组匹配

时间:2016-03-04 00:14:03

标签: javascript arrays regex

我用我正在搜索的字符串创建了一个正则表达式:

var re = new RegExp(searchTerm, "ig");

我有一个我想搜索的数组,其中包含以下术语:

var websiteName = [
  "google", "youtube", "twitter", "medium", "amazon", "airbnb", "campaiyn", "uber", "dropbox", "asana",
  "slack", "soundcloud", "reddit", "uscitp", "facebook"
];

如果我的搜索字词为reddit testtest test,我在调用匹配函数时就不会匹配:

  for(var i = 0; i < websiteName.length; i = i + 1) {
    if(websiteName[i].match(re) != null) {
      possibleNameSearchResults[i] = i;
    }
  }

我如何构造我的正则表达式语句,以便当我搜索我的数组时,如果其中一个单词匹配,它仍将返回true?

1 个答案:

答案 0 :(得分:3)

我想你想要这样的东西:

var searchTerm = 'reddit testtest test';

var websiteNames = ["google", "youtube", "twitter", "medium", "amazon", "airbnb", "campaiyn", "uber", "dropbox", "asana", "slack", "soundcloud", "reddit", "uscitp", "facebook"];

// filter the websiteNames array based on each website's name
var possibleNameSearchResults = websiteNames.filter(function(website) {

  // split the searchTerm into individual words, and
  // and test if any of the words match the current website's name
  return searchTerm.split(' ').some(function(term) {
    return website.match(new RegExp(term, 'ig')) !== null;
  });
});

document.writeln(JSON.stringify(possibleNameSearchResults))

编辑:如果您想要索引而不是项目的实际值,那么最好使用更标准的forEach循环,如下所示:

var searchTerm = 'reddit testtest test',
    websiteNames = ["google", "youtube", "twitter", "medium", "amazon", "airbnb", "campaiyn", "uber", "dropbox", "asana", "slack", "soundcloud", "reddit", "uscitp", "facebook"],
    possibleNameSearchResults = []

// loop over each website name and test it against all of
// the keywords in the searchTerm
websiteNames.forEach(function(website, index) {
  var isMatch = searchTerm.split(' ').some(function(term) {
    return website.match(new RegExp(term, 'ig')) !== null;
  });
  
  if (isMatch) {
    possibleNameSearchResults.push(index);
  }
})

document.writeln(JSON.stringify(possibleNameSearchResults))

相关问题