This code does not work in internet explorer. Any alternative?
"abcde".includes("cd")
This question is related to
javascript
It works for me:
function stringIncludes(a, b) {
return a.indexOf(b) !== -1;
}
I had the same problem when working in Angular 5. In order to make it work directly without writing a polyfill yourself, just add the following line to polyfills.ts file:
import "core-js/es7/array"
Also, tsconfig.json
lib section might be relevant:
"lib": [
"es2017",
"dom"
],
Or just put this in a Javascript file and have a good day :)
String.prototype.includes = function (str) {
var returnValue = false;
if (this.indexOf(str) !== -1) {
returnValue = true;
}
return returnValue;
}
You can do the same with !! and ~ operators
var myString = 'this is my string';
!!~myString.indexOf('string');
// -> true
!!~myString.indexOf('hello');
// -> false
here's the explanation of the two operators (!! and ~ )
What is the !! (not not) operator in JavaScript?
https://www.joezimjs.com/javascript/great-mystery-of-the-tilde/
If you want to keep using the Array.prototype.include()
in javascript you can use this script:
github-script-ie-include
That converts automatically the include() to the match() function if it detects IE.
Other option is using always thestring.match(Regex(expression))
Problem:
Try running below(without solution) from Internet Explorer and see the result.
console.log("abcde".includes("cd"));
_x000D_
Solution:
Now run below solution and check the result
if (!String.prototype.includes) {//To check browser supports or not_x000D_
String.prototype.includes = function (str) {//If not supported, then define the method_x000D_
return this.indexOf(str) !== -1;_x000D_
}_x000D_
}_x000D_
console.log("abcde".includes("cd"));
_x000D_
This one may be better and shorter:
function stringIncludes(a, b) {
return a.indexOf(b) >= 0;
}
includes() is not supported by most browsers. Your options are either to use
-polyfill from MDN https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/includes
or to use
-indexof()
var str = "abcde";
var n = str.indexOf("cd");
Which gives you n=2
This is widely supported.
For react:
import 'react-app-polyfill/ie11';
import 'core-js/es5';
import 'core-js/es6';
import 'core-js/es7';
Issue resolve for - includes(), find(), and so on..
Source: Stackoverflow.com