I have a string:
"0011HelloWor00ld001"
How do I count the number of zeros in the starting of the string? For example, the above string should return 2.
I tried .match(/^[0]+/).size but it doesn't work.
.match(/^0+/) will return a MatchData object, and thus you get 1 as the result (it denotes the number of elements in the match array).
You need to get the size of the match itself. Use one of the following:
"0011HelloWor00ld001".match(/^0+/)[0].size
"0011HelloWor00ld001"[/^0+/].size
"0011HelloWor00ld001".match(/^0+/).to_s.size
You could also simply use the index method of String like
str = '0011HelloWor00ld001'
# as noted by @steenslag if the full string is zeros index will return nil
# solve by returning full string length
str.index(/[^0]/) || str.length
#=> 2
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