I have a code like:
var valid = viewName.contains('/');
which works fine in firefox browser. But in chrome it is undefined
. Why is that so? Is it true that chrome has not such a method for string?
Is it OK to use indexOf
instead of contains
, is it supported in all browsers?
The includes() method returns true if a string contains a specified string. Otherwise it returns false .
To check if a substring is contained in a JavaScript string:Call the indexOf method on the string, passing it the substring as a parameter - string. indexOf(substring) Conditionally check if the returned value is not equal to -1. If the returned value is not equal to -1 , the string contains the substring.
You can use ECMAScript 6's String. prototype. startsWith() method.
The startsWith() method returns true if a string starts with a specified string. Otherwise it returns false .
String.indexOf()
is what I use and it will work fine.
var strIndex = viewName.indexOf('/');
if(strIndex == -1) {
//string not found
} else {
//string found
}
But, just in case you want to have a contains()
function, you can add it to String
as below:
if(!('contains' in String.prototype)) {
String.prototype.contains = function(str, startIndex) {
return -1 !== String.prototype.indexOf.call(this, str, startIndex);
};
}
var valid = viewName.contains('/');
if(valid) {
//string found
} else {
//string not found
}
Support for this, in Firefox and Chrome too, is now disabled by default. If you land here looking for an up to date answer, you can view the reason why, and the new method name (which is String.includes
) here.
Try:
yourString.includes('searchString')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With