Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trim whitespace from the end of a variable

Tags:

string

emacs

I'm looking for an example, please, of how to delete one or more spaces from the end of a variable.

(let ((test-variable "hello "))

  (if (eq ?\s (aref test-variable (1- (length test-variable))))

    (setq test-variable "hello")))
like image 809
lawlist Avatar asked Jan 25 '14 23:01

lawlist


People also ask

How do you remove whitespace at the end of a string?

String result = str. trim(); The trim() method will remove both leading and trailing whitespace from a string and return the result.

Which method can be used to remove whitespace on either end of a variable?

To remove the whitespace from both the beginning and end- Here, we are applying thetrim() method on string variable myStr, as result, trim method removes the leading and trailing whitespaces and returns the trimmed string after removing whitespaces from myStr string variable.

How do you remove whitespace from the beginning and end of a $string variable?

In JavaScript, trim() is a string method that is used to remove whitespace characters from the start and end of a string.

How do I remove a trailing space from a Unix variable?

`sed` command is another option to remove leading and trailing space or character from the string data. The following commands will remove the spaces from the variable, $myVar using `sed` command. Use sed 's/^ *//g', to remove the leading white spaces. There is another way to remove whitespaces using `sed` command.


1 Answers

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))
like image 153
Bozhidar Batsov Avatar answered Oct 08 '22 04:10

Bozhidar Batsov