Coffeescript - Finding substring with "in" -
in coffeescript following gives true
"s" in "asd" # true
but gives false
"as" in "asd" # false
- why this?
- it happens strings more 1 character?
- is
in
not suited task?
x in y
syntax coffeescript expects y
array, or array object. given string, convert array of characters (not directly, iterate on string's indexes if array).
so use of in
:
"as" in "asd" # => false
is equivalent
"as" in ["a","s","d"] # => false
this way easier see why returns false.
the little book of coffeescript has on in
:
includes
checking see if value inside array typically done indexof(), rather mind-bogglingly still requires shim, internet explorer hasn't implemented it.
var included = (array.indexof("test") != -1)
coffeescript has neat alternative pythonists may recognize, namely in.
included = "test" in array
behind scenes, coffeescript using array.prototype.indexof(), , shimming if necessary, detect if value inside array. unfortunately means same in syntax won't work strings. need revert using indexof() , testing if result negative:
included = "a long test string".indexof("test") isnt -1
or better, hijack bitwise operator don't have -1 comparison.
string = "a long test string" included = !!~ string.indexof "test"
personally, bitwise hack isn't legible, , should avoided.
i write check either indexof
:
"asd".indexof("as") != -1 # => true
or regex match:
/as/.test "asd" # => true
or if using es6, use string#includes()
Comments
Post a Comment