Using .includes method in a function
You can use String.indexOf()
instead of String.includes
, As it is available in ES6 and not supported in IE at all.
typeof value == "string" && value.indexOf('$') > -1
Also note if value
is not string type it will still raise an error boolean
, Number
doesn't the the method. You can use typeof
to validate whether value
is a string.
The .includes()
API is part of the String
and Array
data type.
So what the error is trying to tell you is that the value for variable value
, e.g. an integer or object, does not have the property .includes
.
You could do checks like
typeof a_string === 'string'
an_array instanceof Array
before the .includes()
api to prevent this.
Obviously this will make your if statement rather ugly due to the number of checks you have.
Based on the way your code is written I suspect you are more interested in checking "String" than array. So becareful of arrays. Your code may not work properly if it is array.
Anyway here is a refractored version of your code.
function replacer(key, value) {
// Filtering out properties
if (!value || typeof value === "string" && value.includes("$")) {
return undefined;
}
return value;
}
console.log("NULL returns:" + replacer('test', null));
console.log("$Test returns:" + replacer('test', '$test'));
console.log("Blah returns:" + replacer('test', 'Blah'));
I solved this error, which I was getting when applying "includes" to a "window.location" value, by appending ".toString();"
var requestUrl = window.location.toString();
if (requestUrl.includes(urlBase + "#")) { ...
Just one more possibility: Maybe your value
is not a string type object.
(typeof(value) == "string" && value.includes("$"))