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

标签 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?

最佳答案

我想你想要这样的东西:

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))

关于javascript - 使用正则表达式将字符串与数组匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35785655/

相关文章:

创建的文件中没有任何内容

php - 关于数组的一个非常简单的问题

Python 正则表达式替换反斜杠或前斜杠

php - 提取文件名的一部分

javascript - 如何使用meteorhacks :npm package?调用这个wordcount函数

javascript - 使用ajax jquery将变量传递给php页面?

java - 使用 While 与 If 防止数组中出现重复的整数 ID 号

regex - 可以在 if 条件下比较部分字符串吗?

javascript - 从 API 收到的值

javascript - VBA 提取 HTML CDATA