Reputation: 5
I have a string that might end with multiple \n
(the two symbols, not a newline).
How can I remove that from the end of the string?
For example: abc\ndef\n\n
should become abc\ndef
Thanks
Upvotes: 0
Views: 2934
Reputation: 20699
For such a simple task a simple trim()
would suffice:
assert 'abc\ndef' == 'abc\ndef\n\n\n\n'.trim()
Upvotes: 1
Reputation: 2133
You can do it like this:
s = "abc\ndef\n\n"
assert s.replaceAll(/\n*$/, "") == "abc\ndef"
The section between //
looks for any amount of \n
and the $
represents the end of the string. So, replace any amount of newlines with nothing else after them, with an empty string.
Upvotes: 2