Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I compare a string with several values? [duplicate]

Tags:

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?

like image 663
Diego Avatar asked Oct 08 '12 12:10

Diego


People also ask

What are the 3 ways to compare two string objects?

There are three ways to compare String in Java: By Using equals() Method. By Using == Operator. By compareTo() Method.

How do I compare multiple string values in python?

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.

Can you use == to compare two strings?

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.


2 Answers

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 ) ) { ... }
  • MDN on Array.prototype.includes()
like image 143
Sirko Avatar answered Nov 01 '22 11:11

Sirko


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.

like image 30
WTK Avatar answered Nov 01 '22 12:11

WTK