2016-03-04 37 views
3

我创造了我寻找的字符串正则表达式匹配:使用正则表达式来一个字符串数组

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?

+0

为什么不遍历websiteName数组并使用每个元素作为字符串的正则表达式搜索项。 – nick

回答

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

+0

谢谢!是否有anywa返回搜索结果的索引而不是实际值? – ogk

+0

@ogk - 当然,我已经编辑了我的答案,以显示另一个提供索引而不是值的示例。 –

相关问题