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

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

I use it to highlight search results.

The problem is that if I search for something like "café" , it will not highlight any words.

And if I search for “cafe” , although my results contain both “cafe and cafe” , it will only highlight “cafe” .

So, I will need to highlight all the “versions” of words with or without diacritics.

Is it possible?

+6
source share
1 answer

http://jsfiddle.net/nHGU6/

HTML testing:

  <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 test:

  .yellow {
     background-color: # ffff00;
 }

Javascript replacement:

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 }); }); 
+3
source

Source: https://habr.com/ru/post/888611/


All Articles