Why javascript contains property is not working in chrome browser? I have tried that Contains Property in javascript.It is working fine in Mozila Firefox Browser. But It is
Use your own contains method and override firefox's contains() method. Because this method is widely used I mean -> (indexof
).
String.prototype.contains = function(str) { return this.indexOf(str) != -1; };
You must understand why contains is not working. Actually there are two methods contains and includes and both have different usage.
contains :
The contains() method returns a Boolean value indicating whether a node is a descendant of a specified node.
A descendant can be a child, grandchild, great-grandchild, and so on.
var span = document.getElementById("mySPAN");
var div = document.getElementById("myDIV").contains(span);
The result of div will be:
true
please find jsfiddle
includes :
Check if a string includes with "world":
var str = "Hello world, welcome to the universe.";
var n = str.includes("world");
The result of n will be:
true
Definition and Usage
The includes() method determines whether a string contains the characters of a specified string.
This method returns true if the string contains the characters, and false if not.
Note: The includes() method is case sensitive.
Please find jsfiddle
And finally ofcourse you can also use indexOf method to achive same output
var ClearFilterValue = 'family Schools';
alert(ClearFilterValue.indexOf("family") != -1);
Hope this make sense
contains is not supported in Chrome, but you could use a polyfill:
if (!String.prototype.contains) {
String.prototype.contains = function(s) {
return this.indexOf(s) > -1
}
}
'potato'.contains('tat') // true
'potato'.contains('tot') // false
indexof returns the position of the string. If not found, it will return -1:
var ClearFilterValue = 'family Schools';
alert(ClearFilterValue.indexOf("family") != -1);
I think you should be using indexOf
var ClearFilterValue = 'family Schools';
if(ClearFilterValue.indexOf("family") !== -1) {
alert('Success');
}
Also not sure if you should be making a polyfill as pretty much no browser seems to support it anyways https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/contains
None of IE's support it, Chrome apparently starting at 30, FF starting at 19, and i doubt mobile browsers support it either
Actually String.contains
is not supported in Chrome as per the MDN
Here's the way to resolve the issue:
Polyfill
You can easily polyfill this method :
if (!('contains' in String.prototype)) String.prototype.contains = function (str, startIndex) {
return -1 !== String.prototype.indexOf.call(this, str, startIndex);
};
var ClearFilterValue = 'family Schools';
if (ClearFilterValue.contains("family") == true) {
alert('Success');
}
Demo: Fiddle