in Ruby, I just want to get rid of the last n characters of a string, but the following doesn't work
"string"[0,-3]
nor
"string".slice(0, -3)
I'd like a clean method, not anything like
"string".chop.chop.chop
it may be trivial, please anyone teach me! thanks!
Using String. The easiest way is to use the built-in substring() method of the String class. In order to remove the last character of a given String, we have to use two parameters: 0 as the starting index, and the index of the penultimate character.
slice() method to remove the last 3 characters from a string, e.g. const withoutLast3 = str. slice(0, -3); . The slice method will return a new string that doesn't contain the last 3 characters of the original string.
You can use ranges.
"string"[0..-4]
You could use a regex with gsub ...
"string".gsub( /.{3}$/, '' )
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