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.
str is exactly one of those 3 values... )/^(?:foo|bar|baz)$/. The ?: means 'don't bother remembering which one of these three matches', and it might be a bit fastera|b|c? How does it make a difference?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.
/^foo|bar$/ is ^foo OR bar$, and thus would match "fools", and would also match "sandbar".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.
str is a string value... It can't be an object.:) When I said "string value", I meant a value of the String type, not a String object... (String objects are useless, I would never use them... )