Highlight words with (and without) accented characters / diacritics in jQuery

故事扮演 提交于 2019-12-12 08:38:53

问题


I'm using the jquery.highlight plugin: http://code.google.com/p/gce-empire/source/browse/trunk/jquery.highlight.js?r=2

I'm using it to highlight search results.

The problem is that if I search something like "café" it won't highlight any words.

And if I search "cafe", even though my results contains both "cafe" & "café", it will only highlight "cafe".

So, I would need to highlight all "versions" of the words, with or without diacritics.

Is that possible?


回答1:


http://jsfiddle.net/nHGU6/

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

Test CSS:

.yellow {
    background-color: #ffff00;
}

Replacement 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);
    });
};

Test code:

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



回答2:


I can recommend a good library that supports this out of the box: highlight.js. While it is designed to do syntax highlighting for code blocks, you can equally as well highlight other (key-)words by defining an according language syntax grammar.

Setting the option of lexemes : '[äöüÄÖÜßa-zA-Z]+' in your language specification will enable keywords with German special characters, for example.



来源:https://stackoverflow.com/questions/6067344/highlight-words-with-and-without-accented-characters-diacritics-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!