Remove only TRAILING whitespace

B

Bob Smyph

Is there any way to only remove trailing white space from a string. I
have tried to use strip but that will also take off leading white space
and I want to keep that.

any help is appreciated
 
T

The Higgs bozo

Bob said:
Is there any way to only remove trailing white space from a string. I
have tried to use strip but that will also take off leading white space
and I want to keep that.

any help is appreciated

irb(main):001:0> "sldkfj ".sub(/\s+\Z/, "")
=> "sldkfj"
 
L

Lyle Johnson

Is there any way to only remove trailing white space from a string. I
have tried to use strip but that will also take off leading white space
and I want to keep that.

String#rstrip will remove just the white space on the end (the "right"
side) of the string. Likewise, String#lstrip removes leading white
space only. And you already know about String#strip. ;)
 
S

Stephen Ball

str = " string "

rightTrim = str.rstrip
=> " string"

# for completeness
leftTrim = str.lstrip
=> "string "
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top