Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 449
Santiago Avatar asked May 20 '11 04:05

Santiago


1 Answers

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 });
});
like image 133
anon Avatar answered Oct 06 '22 00:10

anon