Possible Duplicate:
array.contains(obj) in JavaScript
Something like:
if (mystring == "a" || mystring == "b" || mystring =="c")
I was hopping to do:
if (mystring in ("a", "b", "c"))
is it possible?
There are three ways to compare String in Java: By Using equals() Method. By Using == Operator. By compareTo() Method.
To compare a string to multiple items in Python, we can use the in operator. We have the accepted_strings list. Then we can use the in operator to check if facility included in the accepted_strings list. Since this is True , 'accepted' is printed.
You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not. On the other hand, equals() method compares whether the value of the strings is equal, and not the object itself.
You could use indexOf()
like this
if ( [ 'a', 'b', 'c' ].indexOf( mystring ) > -1 ) { ... }
EDIT With ES7 comes a little simplification. As of today just Chrome 47+ and FF 43+ seem to support it:
if ( [ 'a', 'b', 'c' ].includes( mystring ) ) { ... }
Array.prototype.includes()
Using indexOf is first thing that comes to mind, however you have to keep in mind, that there's no .indexOf
function in older IEs (so you would have to use your custom code to simulate it, or just go straight to something like jQuery.inArray or underscore.js indexOf).
if ([ 'a', 'b', 'c' ].indexOf( mystring ) > -1 ) { ... }
Side note: as you can see by looking at inArray definition in jQuery source, writing your own indexOf replacement is pretty easy. So like I said - write your own method, copy-paste it from other libraries or just use those libs if you want to be able to use indexOf in every browser out there.
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