4

I have this case insensitive custom selector :

jQuery.expr[':'].Contains = function(a,i,m) {
    var text = jQuery(a).text().toUpperCase();
    var words = m[3].split(/\s+/);
    for(var i = 0; i < words.length; i++) {
        if (-1 == text.indexOf(words[i].toUpperCase())) {
          return false;
        }
    }
    return true;
};

It works fine, but it gets messed up with accents. My question is thus simple, how could I make this selector both case and accent insensitive?

I was thinking of using a character map with regex, but I can't seem to make it run properly.

Thanks for your help.

morgi
  • 1,005
  • 3
  • 17
  • 24

2 Answers2

4

I found this on Github, it works great for me : https://gist.github.com/oziks/3664787

jQuery.expr[':'].contains = function(a, i, m) {
    var rExps=[
        {re: /[\xC0-\xC6]/g, ch: "A"},
        {re: /[\xE0-\xE6]/g, ch: "a"},
        {re: /[\xC8-\xCB]/g, ch: "E"},
        {re: /[\xE8-\xEB]/g, ch: "e"},
        {re: /[\xCC-\xCF]/g, ch: "I"},
        {re: /[\xEC-\xEF]/g, ch: "i"},
        {re: /[\xD2-\xD6]/g, ch: "O"},
        {re: /[\xF2-\xF6]/g, ch: "o"},
        {re: /[\xD9-\xDC]/g, ch: "U"},
        {re: /[\xF9-\xFC]/g, ch: "u"},
        {re: /[\xC7-\xE7]/g, ch: "c"},
        {re: /[\xD1]/g, ch: "N"},
        {re: /[\xF1]/g, ch: "n"}
    ];

    var element = $(a).text();
    var search = m[3];

    $.each(rExps, function() {
        element = element.replace(this.re, this.ch);
        search = search.replace(this.re, this.ch);
    });

    return element.toUpperCase()
    .indexOf(search.toUpperCase()) >= 0;
};
Erwan
  • 2,512
  • 1
  • 24
  • 17
0

Instead of using string.indexOf(), use string.match() with the regular expression insensitive option.

Something like:

if (!text.match(new RegExp(words[i],'i'))){
   return false;
}

RegExp comparisions take into account Unicode characters, so the accents will be correctly matched between upper and lowercase.

iCollect.it Ltd
  • 92,391
  • 25
  • 181
  • 202