String contains not working in IE - javascript

I am trying to use contains to find out if a phrase appears within a string
The code below works fine in FF and Chrome, however IE8-10 return an error.
SCRIPT438: Object doesn't support property or method 'contains'
var str = "This is a string";
if(str.contains("string")){
alert('Yes'};
}
Not sure why IE is throwing a error so any help would be much appreciated.

The .contains() function is an ES2015 feature that older Internet Explorer versions don't support.
The MDN page has a polyfill:
if ( !String.prototype.contains ) {
String.prototype.contains = function() {
return String.prototype.indexOf.apply( this, arguments ) !== -1;
};
}
A general guide for questions like this: type MDN something into the Google search box. If you don't find a result, then "something" probably doesn't exist in the JavaScript universe. If you do, then there's a pretty good chance that you'll find the answer you seek there.

Related

Array.prototype.find() vs IE11

https://caniuse.com/#search=find states The find() method is not supported by IE11.
At the same time I'm testing this find() method in IE11 and I didn't find any traces of any wrong behavior.
I've also tested in IE11 the code
function isPrime(element, index, array) {
var start = 2;
while (start <= Math.sqrt(element)) {
if (element % start++ < 1) return false;
}
return (element > 1);
}
console.log([4, 5, 8, 12].find(isPrime)); // 5
from
SO: Array.prototype.find() is undefined
Yes, in IE11 it returns the expected result of 5 instead of TypeError: undefined is not a function, as SO: Array.prototype.find() is undefined in 2014 stated.
So... Am I missing something and IE11 really doesn't work properly with Array.prototype.find , or the last updates of IE11 that were made a while ago (but later than the SO question above was discussed in 2014) became to support this method?
Is https://caniuse.com/#search=find correct when says IE11 doesn't support Array.prototype.find ? Any evidence?
Thank you.
UPD: here is the screen of my IE11:
Everything you have read is correct. There is something flawed about your tests. Perhaps you included a Polyfill that added the method in IE11.
You can try following steps to validate:
Open a blank tab in IE.
Open console in dev tools.
Enter following code: [1,2,3].find(function(n) { !!n; })
If above code throws error (which it should), you are using a polyfill. Hence your code does not break.
If it works, only explanation is that somehow, some update has added its definition. But this is very unlikely as MS has stopped support for it.
This is what I get:

Javascript ES6 TypeError in Safari & IE

I am working with a Javascript code written by someone else who used ES6 in a Wordpress site. It makes an Ajax call to show a data in DOM, which works for Chrome and Firefox but for some reason Safari gives following error in console:
TypeError: document.querySelectorAll(".js_zip-lookup__submit").forEach is not a function. (In 'document.querySelectorAll(".js_zip-lookup__submit").forEach(function(e){e.addEventListener("click",function(){displayResults(e.parentNode.querySelector(".zip-lookup__input").value)})})', 'document.querySelectorAll(".js_zip-lookup__submit").forEach' is undefined)
This is the function:
function finderInit(){
document.querySelectorAll('.js_zip-lookup__submit').forEach(function(button){
button.addEventListener('click', function(){
const zip = button.parentNode.querySelector('.zip-lookup__input').value;
displayResults(zip);
});
});
document.querySelectorAll('.zip-lookup').forEach(function(form){
form.addEventListener('submit', function(e){
e.preventDefault();
const zip = form.querySelector('.zip-lookup__input').value;
displayResults(zip);
})
});
}
And I can't quite tell why Safari would have an issue with this, while Chrome/FF doesn't even log any error about this particular part in the console and it works just fine. I know it should be some browser compatibility issue but haven't found much information so far.
document.querySelectorAll returns NodeList object, not an array. As it can be seen on MDN, NodeList has forEach method but it's not well-supported, that's why it works in recent Firefox and Chrome but not in other browsers (Safari):
Although NodeList is not an Array, it is possible to iterate on it using forEach(). Several older browsers have not implemented this method yet.
To iterate over node lists and other iterators in a compatible way, Array.from should be used (can be polyfilled in older browsers):
Array.from(document.querySelectorAll(".js_zip-lookup__submit")).forEach(...);
I tried many variations of Array.prototype, but the only thing that solved IE & Safari compatibility issue was inclusion of this polypill snippet below, solution found in this blog:
(function () {
if ( typeof NodeList.prototype.forEach === "function" ) return false;
NodeList.prototype.forEach = Array.prototype.forEach;
})();
As mentioned by #Estus, older versions of Safari do not implement .forEach on nodelist objects. However, Array.prototype.forEach is defined as generic in the ES5.1 specifiction:
The forEach function is intentionally generic; it does not require that its this value be an Array object. Therefore it can be transferred to other kinds of objects for use as a method. Whether the forEach function can be applied successfully to a host object is implementation-dependent.
Hence a workable solution is to call Array.prototype.forEach on the nodelist and pass it the function you want to execute. As a cut down (and cheap) test case:
var col = document.getElementsByTagName("p");
//col.forEach( function (el) {document.write(el.id)});
Array.prototype.forEach.call(col, function (el) {document.write(el.id)});
<p id="p1"></p>
<p id="p2"></p>
<p id="p3"></p>
<p id="p4"></p>
This was tested and found to work in Safari 5.1.7 for Windows and under Internet. Explorer 9 emulation. The commented out line reproduces the error reported in the post in Safarai 5.1.7.

How to collect only unique values in an Array in Internet Explorer 11 by JavaScript?

from many articles I have chosen this syntax to make unique values in an array.
pairs = pre_final_pairs.filter((elem, index) => pre_final_pairs.indexOf(elem) === index).join(' ');
This works perfectly in all browsers except Internet Explorer 11.
I have tried to find which of the command from the line is not compatible and I found that maybe the indexOf. But even if I tried to apply "fix" referred in How to fix Array indexOf() in JavaScript for Internet Explorer browsers still the page is not working in the IE11.
Also I have loaded https://code.google.com/archive/p/ddr-ecma5/ library in order to ensure that the ECMA commands will work.
And still getting SCRIPT1002: Syntax error
Do you see there a wrong part in the command?
Internet Explorer does support indexOf, but does not support arrow functions.
You can easily fix that using a regular function for the callback instead:
pairs = pre_final_pairs.filter(
function (elem, index) {
return pre_final_pairs.indexOf(elem) === index;
}
).join(' ');

Javascript error (SCRIPT5022) in IE10

I wrote this code:
AjxException.reportScriptError =
function(ex) {
if (AjxException.reportScriptErrors && AjxException.scriptErrorHandler && !(ex
instanceof AjxException)) {
AjxException.scriptErrorHandler(ex);
}
throw ex;
};
it's fine in all browsers including IE9,8 but I got this error in IE10:
SCRIPT5022: InvalidCharacterError
mentioned throw ex;
Why this happens in IE10 and how could I solve this?
eventually, I figured out what was wrong with the codes:
the javascript code was written for old versions of IE: IE7, IE8, IE9 and used this line:
var ninput = document.createElement(AjxEnv.isIE ? ["<INPUT type='",type,"'>"].join("") :
"INPUT");
in order to create INPUT element. it works fine in older versions of IE but not in IE10.
So, I had to use this one instead:
var ninput = document.createElement((AjxEnv.isIE && !AjxEnv.isIE10up)? ["<INPUT
type='",type,"'>"].join("") : "INPUT");
now, it's working.
Are your files saved without a BOM (Byte Order Mark)? Those can often throw off parsers and wreak havoc.
I'd also recommend chopping up your code in to as many lines as possible to determine which line has the issue and then remove it for testing purposes and that way you'll be able to quickly determine what the issue is.
For example you may be referring to an object of the wrong type (working with an array and the object happens to be a string for example) so if you remove an object and it works (or works slightly better) try alert('typeof myObject = '+typeof myObject); to give you some further insight.
Also it looks like you have multiple instances of ex, make sure you aren't using a string and a function both named ex.

"SCRIPT438: Object doesn't support property or method 'url' " in IE only

I am getting the following error in IE (but not Firefox):
SCRIPT438: Object doesn't support property or method 'url'
AjaxSetup.js?version=7b8dcb65-17d1-437f-9594-0621c779427c, line 28 character 2
There are several other posts with errors like this (for other objects besides url), but all of them seem to have answers along the lines of "such a function doesn't exist in jquery" or "such a function is invalid to use in this context", and neither seems to apply to my situation at least as far as I can tell.
The function containing the line number that the error is referring to is:
function redirectToLogin() {
var redirUrl = $.url().attr("path");
if ($.url().attr("query").length > 0) {
redirUrl += "?" + $.url().attr("query");
}
top.window.location = "/Shared/Logout?redir=" + encodeURIComponent(redirUrl);
return;
}
where line 28 is the second line of the function above.
More strangely, while on the offending page (from which the above function gets called), when I type $.url() or $.url().attr("path") into the IE Developer Tools console, it returns the correct object and string, respectively. The values also seem to stay correct if I "watch" them.
Any help would be much appreciated!
EDIT:
I found a workaround:
function redirectToLogin() {
top.window.location = "/Shared/Logout?redir=" + encodeURIComponent(location.pathname + location.search);
return;
}
This seems to work and achieve the same thing, so I'm posting it in case it helps someone. However, I would still be curious to find out why the original code using jquery was not working.
I would guess if you say it works in the console that the code is trying to use it before $.url() is initialized. Is the url JavaScript included before the AjaxSetup file?

Categories

Resources