Given a variable str
containing a string value, are these two lines of code equivalent?
Line A:
if ( [ 'foo', 'bar', 'baz' ].indexOf( str ) > -1 ) {
Line B:
if ( /^foo|bar|baz$/.test( str ) ) {
Given a variable str
containing a string value, are these two lines of code equivalent?
Line A:
if ( [ 'foo', 'bar', 'baz' ].indexOf( str ) > -1 ) {
Line B:
if ( /^foo|bar|baz$/.test( str ) ) {
Not quite. The pipes are including the ^
and $
as alternatives. I'm not entirely clear on the syntax of JS's regular expressions, but if you're looking for str
to contain only foo
, or bar
, or baz
, use the expression /^(foo|bar|baz)$/
. If you're looking to do something different, let me know and I'll try to clear it up.
Okay, after the edit, they're still not equivalent since test
will call toString
. See:
var myItem = {toString: function() { return 'foo'; }};
['foo', 'bar', 'baz'].indexOf(myItem); // -1
/^(foo|bar|baz)$/.test(myItem); // true
Even when they're string values (sorry, missed that) then they're still not equivalent because there are two different types of strings and indexOf
uses strict equality/identity:
To make them truly equivalent, you can either call .toString()
before using indexOf
, or you can test Object.prototype.toString.call(myItem) === '[object String]'
before using test
.
No, they are not.
The method indexOf()
returns -1
if the item is not found in the array, or the position of the array if it is found in the array.
The method test
returns true
if the regex finds a match, and false
if it doesn't.
If your regular expression was instead /^(foo|bar|baz)$/
, then the function would be the same.