How to trim whitespace from the end of a variable

Or

(replace-regexp-in-string "\s+$" "" "bar    ")
"bar"

Simple: (car (split-string "hello ")) ==> "hello"

You can also explicitly use argument TRIM, as the doc string recommends:

(split-string "hello   "
              split-string-default-separators
              t
              split-string-default-separators)

In Emacs 24.4 (which is to be released later this year) this will be even simpler:

(require 'subr-x)

(string-trim-right "some string  ")

While you're waiting for 24.4 to come you can simply define string-trim-right locally:

(defun string-trim-right (string)
  "Remove trailing whitespace from STRING."
  (if (string-match "[ \t\n\r]+\\'" string)
      (replace-match "" t t string)
    string))

Tags:

String

Emacs