2013-08-04 229 views
0

我在下面的此JavaScript代碼搜索任何單詞輸入到文本字段。現在,需要搜索的文本在這個示例文本中包含特殊字符,如撇號和點:「和Zeb'uun的部落。」搜索文本中的特殊字符

現在,我該如何採用我的JS代碼來包含這些特殊字符?如果我在我的文本框中輸入沒有特殊字符的Zebulun,則搜索功能找不到它。

var SearchResultCount = 0; 
    var a = new Array(); 
    var oneTime = false; 

    // helper function, recursively searches in elements and their child nodes 
    function HighlightAllOccurencesOfStringForElement(element,keyword) { 
     if (element) { 
      if (element.nodeType == 3) { // Text node 
       while (true) { 
        var value = element.nodeValue; // Search for keyword in text node 
        var idx = value.toLowerCase().indexOf(keyword; 

        if (idx < 0) break; // not found, abort 

        var span = document.createElement("span"); 
        var text = document.createTextNode(value.substr(idx,keyword.length)); 
        span.appendChild(text); 
        span.setAttribute("class","MyAppHighlight"); 

        text = document.createTextNode(value.substr(idx+keyword.length)); 
        element.deleteData(idx, value.length - idx); 
        var next = element.nextSibling; 
        element.parentNode.insertBefore(span, next); 
        element.parentNode.insertBefore(text, next); 
        element = text; 

        span.scrollIntoView(); 
        span.style.background= "-webkit-linear-gradient(top, #FAE309, #FFF7AA)"; 
        span.style.fontWeight = "bold"; 
        span.style.padding = "2px"; 
        span.style.borderRadius = "5px"; 
        span.style.boxShadow = "0px 0px 2px black"; 
        a.push(span); // SET THIS CODE HERE 
        SearchResultCount++; // update the counter 
       } 

      } else if (element.nodeType == 1) { // Element node 
       if (element.style.display != "none" && element.nodeName.toLowerCase() != 'select') { 
        for (var i=element.childNodes.length-1; i>=0; i--) { 
         HighlightAllOccurencesOfStringForElement(element.childNodes[i],keyword); 
        } 
       } 
      } 
     } 
    } 

// the main entry point to start the search 
function HighlightAllOccurencesOfString(keyword) { 
    RemoveAllHighlights(); 
    HighlightAllOccurencesOfStringForElement(document.body, keyword.toLowerCase()); 
} 

回答

0

首先,有一個右括號下面一行丟失:

var idx = value.toLowerCase().indexOf(keyword; 

所以,我不會感到驚訝,如果該功能沒有在所有的工作。

要回答您的問題,一種方法是使用字符串變量的原生replace()函數清除除字母字符以外的每個字符。您必須對搜索字詞這兩個字詞進行搜索,因此您必須通過該函數傳遞valuekeyword變量。事情是這樣的:

keyword = cleanUp(keyword); 
var value = cleanUp(element.nodeValue); 
... 
function cleanUp(toClean) { 
    cleaned = toClean.replace([^a-zA-Z],""); //Deletes non-alphabetic characters (including spaces) by replacing them with nothing. If you want to leave spaces intact, use [^a-zA-Z ] instead. 
    return cleaned; 
} 

一旦做到這一點,使用相同的功能,你必須要兩個字符串進行比較。