Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using contains instead of stringStartsWith knockout js

I have the folliwng on my model:

self.filteredItems = ko.computed(function () {
            var filter = this.filter().toLowerCase();

            if (!filter) {
                return this.sites();
            } else {
                return ko.utils.arrayFilter(this.sites(), function (item) {
                    return ko.utils.stringStartsWith(item.Name().toLowerCase(), filter);
                });
            }

        }, self);

I use it for a search on my page but rather than stringStartsWith I'd like some sort of .contains instead so I get results where my searchterm is contained anywhere in the string rather than just at the beginning.

I imagine this must be a pretty common request but couldnt find anything obvious.

Any suggestion?

like image 571
Simon Avatar asked Jul 09 '13 20:07

Simon


1 Answers

You can use simply the string.indexOf method to check for "string contains":

self.filteredItems = ko.computed(function () {
    var filter = this.filter().toLowerCase();

    if (!filter) {
        return this.sites();
    } else {
        return ko.utils.arrayFilter(this.sites(), function (item) {
            return item.Name().toLowerCase().indexOf(filter) !== -1;
        });
    }

}, self);
like image 187
nemesv Avatar answered Sep 22 '22 15:09

nemesv