2016-03-04 81 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 - 當然,我已經編輯了我的答案,以顯示另一個提供索引而不是值的示例。 –

相關問題