9

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?

Simon
  • 1,966
  • 5
  • 21
  • 35
  • possible duplicate of [Method like String.contains() in JavaScript](http://stackoverflow.com/questions/1789945/method-like-string-contains-in-javascript), because answers are about String functions, more than Knockout or ASP.NET – Brigand Jul 10 '13 at 21:35

1 Answers1

15

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);
nemesv
  • 138,284
  • 16
  • 416
  • 359