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.
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>
As the MDN article you linked to says, Firefox only supports .includes
in nightly builds, other browsers didn't support it at all at the time the article was last updated (Chrome may have been updated to support it at a later time). If you want to support all browsers, you can use the polyfill outlined in the same article:
if (![].includes) {
Array.prototype.includes = function(searchElement /*, fromIndex*/ ) {
'use strict';
var O = Object(this);
var len = parseInt(O.length) || 0;
if (len === 0) {
return false;
}
var n = parseInt(arguments[1]) || 0;
var k;
if (n >= 0) {
k = n;
} else {
k = len + n;
if (k < 0) {k = 0;}
}
var currentElement;
while (k < len) {
currentElement = O[k];
if (searchElement === currentElement ||
(searchElement !== searchElement && currentElement !== currentElement)) {
return true;
}
k++;
}
return false;
};
}
However, it sounds like your problem has a better solution, but it's hard to tell without any specifics.