2011-05-20 44 views
6

變音符號我用jquery.highlight插件亮點的話:http://code.google.com/p/gce-empire/source/browse/trunk/jquery.highlight.js?r=2與(和不)重音字符/ jQuery中

我用它來突出顯示搜索結果。

問題是,如果我搜索類似「café」它不會突出顯示任何單詞。

如果我搜索「咖啡館」,即使我的結果既包含「咖啡館」 & 「吃茶」,它將只強調「咖啡館」

所以,我需要突出顯示單詞的所有「版本」,有或沒有變音符號。

這可能嗎?

+0

查看來自casablanca的答案:http://stackoverflow.com/questions/4261740/accent-insensitive-regex。基本上,圍繞jquery.highlight.js的第91行進行修改,以便正則表達式現在包含字符類。可能會在第83行附近添加「accentInsensitive」選項。 – anon 2011-05-20 04:16:35

+0

謝謝,但是我對如何在代碼中實現該代碼感到有點遺憾... – Santiago 2011-05-20 21:28:39

+0

好的。我在下面添加了一個實現。 – anon 2011-05-21 01:23:04

回答

3

http://jsfiddle.net/nHGU6/

測試HTML:

 
<div id="wrapper-accent-sensitive"> 
<p>cafe</p> 
<p>asdf</p> 
<p>café</p> 
</div> 
<hr /> 
<div id="wrapper-not-accent-sensitive">> 
<p>cafe</p> 
<p>asdf</p> 
<p>café</p> 
</div> 

測試CSS:

 
.yellow { 
    background-color: #ffff00; 
} 

更換的Javascript:

jQuery.fn.highlight = function (words, options) { 
    var accentedForms = { 
     'c': 'ç', 
     'e': 'é' 
    }; 

    var settings = { className: 'highlight', element: 'span', caseSensitive: false, wordsOnly: false, accentInsensitive: false }; 
    jQuery.extend(settings, options); 

    if (settings.accentInsensitive) { 
     for (var s in accentedForms) { 
      words = words.replace(s, '[' + s + accentedForms[s] + ']'); 
     } 
    } 

    if (words.constructor === String) { 
     words = [words]; 
    } 

    var flag = settings.caseSensitive ? "" : "i"; 
    var pattern = "(" + words.join("|") + ")"; 
    if (settings.wordsOnly) { 
     pattern = "\\b" + pattern + "\\b"; 
    } 
    var re = new RegExp(pattern, flag); 

    return this.each(function() { 
     jQuery.highlight(this, re, settings.element, settings.className); 
    }); 
}; 

測試代碼:

$(document).ready(function() { 
    $("#wrapper-accent-sensitive").highlight("cafe", { className: 'yellow' }); 
    $("#wrapper-not-accent-sensitive").highlight("cafe", { className: 'yellow', accentInsensitive: true }); 
}); 
+0

謝謝,這工作得很好,除了「wordsOnly:true」選項。它必須是新模式的一些問題:pattern =「\\ b」+ pattern +「\\ b」;.另外,你知道這個更完整的變音符列表應該如何在這個代碼中實現嗎? http://lehelk.com/2011/05/06/script-to-remove-diacritics/ – Santiago 2011-05-21 02:01:03

+0

哇。太棒了!顯然,這不是一個簡單的問題。檢查了這一點:http://stackoverflow.com/questions/3693750/how-can-i-make-a-regular-expression-which-takes-accented-characters-into-account。在這種情況下,您可以使用XRegExp庫。至於移除/規範化變音符號(這可能是我上面評論中引用的tchrist解決方案),也許你可以查看http://rishida.net/blog/?p=222。不過,這很殘酷。 – anon 2011-05-21 02:46:46