Question

I'm looking for a plugin/extension to jquerys :contains selector that is case insensitive and only matches up words that starts with the :contains text

In such a way that if you type 'count', you will NOT get 'account' results

Thanks in advance

Edit: I ended up with the following

$.expr.pseudos.Contains = $.expr.createPseudo(function(arg) {
return function(elem) {
  var sentence = $(elem).text().trim().toLowerCase();
  var words = sentence.split(' ');
  arg = arg.toLowerCase();
  var args = arg.split(' ');
  var searchfound = true;

  for(var ix = 0, lx = args.length; ix < lx; ix++) {

    var thisfound = false;

    for(var i = 0, l = words.length; i < l; i++) {
      var wordpos = sentence.indexOf(words[i]);
      var restofsentence = sentence.slice(wordpos, wordpos+args[ix].trim().length);
      if(restofsentence == args[ix].trim() ){             
        thisfound = true;
      }
    }

    if (thisfound == false) {
      searchfound = false;
    }

  }

  return searchfound;  

};
});

It searches from the start of every search entry and returns true if there are matches, regardless of entry order.

Was it helpful?

Solution

You can easily create your own pseudo-selector for that:

$.expr.pseudos.startsWith = $.expr.createPseudo(function(arg) {
    return function(elem) {
        return $(elem).text().trim().slice(0, arg.length).toLowerCase() == arg.toLowerCase();
    };
});

Demo

For matching any word, you need to split them by space and iterate over the collection:

$.expr.pseudos.anyWordStartsWith = $.expr.createPseudo(function(arg) {
    return function(elem) {
        var words = $(elem).text().trim().toLowerCase().split(' ');
        arg = arg.toLowerCase();

        for(var i = 0, l = words.length; i < l; i++) {
            if(words[i].slice(0, arg.length) == arg)
                return true;
        }

        return false;
    };
});

Demo

The function takes the content text() of the subject element, trims any whitespace, converts it to lowercase, for the sake of case insensitive comparison, and splits the string into an array, where space is considered the list separator ("a b c" => ["a", "b", "c"]).

It then converts arg, which is your search phrase, to lowercase, also for the sake of case insensitive comparison.

It continues to iterate over the array of words, and compare the substring of every word with the target phrase. I'm using .slice(0, n) rather than .substring(0, n) because the latter would complain if the length of the subject string was less than n characters.

If any such match is found, the iteration will break immediately, returning true, otherwise it will iterate over the entire collection and reach the last line where it returns false.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top