2013-07-31 37 views
1

我在尋找類似:字符串搜索,忽略「一」,「中」,等用JavaScript

if(magicSearch("hot pizza","We sell pizza that is really hot") {//Found!} 

如果兩個詞出現(任何順序)我只想要一個「真」和我希望它在要搜索的文本中忽略諸如「a」,「和」,「the」等。

(我敢肯定有更好的術語來解釋什麼,我正在尋找)

我見過各種數據庫引擎支持這種類型的文本搜索(如MongoDB的),但我需要一個簡單的JavaScript方式測試字符串。我可以構建它,但它感覺就像某處已經存在的東西。

格雷格

+0

不知道是否已經存在的東西在那裏,但你可以在空白拆分第一個字符串,使用正則表達式'test'方法,如果有失敗則返回false,全部通過則返回true。至於消除「a」,「the」等停用詞,我認爲您需要創建一系列停用詞來剝離,並在測試每個單詞之前將其抽出。 – HartleySan

+1

你想用**停用詞**列表構建啓發式搜索模塊。 – zsong

+0

正如別人在他們的回答中所說的,'indexOf'比正則表達式'test'方法更簡單快捷。對不起,不好的建議。 – HartleySan

回答

2

你可以在一個簡單的循環使用indexOf功能。

//Use this if you don't need to find exact matches of words 
function magicSearch(needles, haystack) { 
    var searchTerms = (needles instanceof Array) ? needles : [needles]; 
    for(var i = 0; i < searchTerms.length; i++) { 
     if(haystack.indexOf(searchTerms[i]) === -1) { 
      return false; 
     } 
    } 
    return true; 
} 

//Use this if you want to find exact matches of words 
function magicSearch2(needles, haystack) { 
    var searchTerms = (needles instanceof Array) ? needles : [needles], 
     haystackArray = haystack.split(' '), 
     index, 
     found = 0; 

    for(var i = 0; i < haystackArray.length; i++) { 
     index = searchTerms.indexOf(haystackArray[i]); 
     if(index !== -1) { 
      delete searchTerms[i]; 
      found++; 
      if(found = searchTerms.length) { 
       return true; 
      } 
     } 
    } 
    return false; 
} 
if(magicSearch(["hot", "pizza"],"We sell pizza that is really hot") { 
    console.log("FOUND"); 
} 
if(magicSearch2(["hot", "pizza"],"We sell pizza that is really hot")) {  
    console.log("FOUND"); 
} 
+0

注意:如果您通過iFrame或窗口邊界共享對象,'(needles instanceof Array)'將無法正常工作,因爲它們將成爲另一個文檔「Array」的實例。 –

1

如果使用underscore.js,你可以有一些相對簡單的實現

var stopwords_set = ["a", "and", "the" ]; 
var magicSearch = function (keywords, str) { 
    var content_set = {}; 
    var keywords_set = {}; 

    _.each(keywords.split(' '), function(item){ 
     keywords_set[item.toLowerCase()] = 1; 
    }); 

    _.each(str.split(' '), function(item){ 
     content_set[item.toLowerCase()] = 1; 
    }); 

    //convert input to 2 sets excluding stop words 
    content_set = _.without(_.keys(content_set), stopwords_set); 
    keywords_set = _.without(_.keys(keywords_set), stopwords_set); 

    //check the intersecion 
    var value = _.intersection(content_set, keywords_set).length == keywords_set.length 
    return value; 
} 

magicSearch("hot pizza","We sell pizza that is really hot");