Use the findlast function in combination with the length function to see if the last character is a space. Then you can use the substring to remove that last space.
If you are using Community Commons, you can use RegexReplaceAll do this.
The Needle Regex needs to be
and the Replacement needs to be
Use the return variable as this will have the trimmed string.
The regular expression first sets itself up to accept multiple lines, tries to grab and memorise as few characters as possible from the start, and then grab as many spaces as possible from then end. We set the replacement to be those memorised characters, which should be the string you need without any trailing whitespace.
Hope this helps.