Search code examples
javascriptarraysecmascript-5ecmascript-2016

Browser support for array.includes and alternatives


I looked it up and found this regarding finding a substring in a larger string in an array. Array.Prototype.includes

if (t.title.includes(searchString))

My t is part of a $.each that's iterating through a larger array of objects (each objects got a buttload of info, from strings, dates and such). searchString is whatever the user typed in a box. All this is a simple search function for a list I have on the page.

This works just fine in Chrome. But Firefox and IE are turning up errors stating

TypeError: currentTicket.title.includes is not a function

So I either put up a warning sign that my app only works on Chrome or I handcraft a find function? Weird thing is the doc page from MDN I posted states that only Firefox supports the array.includes, strangely enough it's only Chrome that runs it.


Solution

  • Instead of using an API that is currently marked as "experimental" consider using a more broadly supported method, such as Array.prototype.indexOf() (which is also supported by IE).

    Instead of t.title.includes(string) you could use t.title.indexOf(string) >= 0

    You can also use Array.prototype.filter() to get a new array of strings that meet a certain criteria, as in the example below.

    var arr = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"];
    document.getElementById("input").onkeyup = function() {
      document.getElementById("output").innerHTML = arrayContainsString(arr,this.value);
    }
    document.getElementById("header").innerHTML = JSON.stringify(arr);
    
    function arrayContainsString(array, string) {
      var newArr = array.filter(function(el) {
        return el.indexOf(string) >= 0;
      });
      return newArr.length > 0;
    }
    <input id="input" type="text" />
    <br/>
    <div>array contains text:<span id="output" />
    </div>
    <div id="header"></div>