Trim whitespace (spaces) from a string

From CodeCodex

Related content:

Contents

Implementations

Common Lisp

Common lisp has a built-in string-trim function. In fact, you can get rid of arbitrary characters. The first parameter is the character you want to get rid of from the right and left of the string, the second parameter is the string.

(string-trim " " " trim me ")
;;output "trim me"

Unsurprisingly, if you want to just get rid of characters on just one end of the string, use string-right-trim or string-left-trim.

Erlang

string:strip("   123 xyz  ").           % "123 xyz"
string:strip("   123 xyz  ", left).     % "123 xyz  "
string:strip("   123 xyz  ", right).    % "   123 xyz"
string:strip("...123 xyz..", both, $.). % "123 xyz"

Java

The String class in Java has a built in trim function:

  String s = "  xyz  ".trim();
  System.out.println(s);  // prints out "xyz";

According to Java document:

If this String object represents an empty character sequence, or the first and last characters of character sequence represented by this String object both have codes greater than '\u0020' (the space character), then a reference to this String object is returned.

If you want to trim an empty character sequence " " to "", trim() works (in this case, trim will return the empty string).

JavaScript

Trim is not built into JavaScript, but you can use prototyping to add this to your code:

String.prototype.trim = function() {
   return this.replace(/^\s+|\s+$/g,"");
}

Then you can use this code like this example:

var input = "   xyz   ";
var output = input.trim();    // output = "xyz"

OCaml

      
let rec trim s =
  let l = String.length s in 
  if l=0 then s
  else if s.[0]=' ' || s.[0]='\t' || s.[0]='\n' || s.[0]='\r' then
    trim (String.sub s 1 (l-1))
  else if s.[l-1]=' ' || s.[l-1]='\t' || s.[l-1]='\n' || s.[l-1]='\r' then
    trim (String.sub s 0 (l-1))
  else
    s

another solution:

let trim str =
  if str = "" then "" else
  let search_pos init p next =
    let rec search i =
      if p i then raise(Failure "empty") else
      match str.[i] with
      | ' ' | '\n' | '\r' | '\t' -> search (next i)
      | _ -> i
    in
    search init
  in
  let len = String.length str in
  try
    let left = search_pos 0 (fun i -> i >= len) (succ)
    and right = search_pos (len - 1) (fun i -> i < 0) (pred)
    in
    String.sub str left (right - left + 1)
  with
  | Failure "empty" -> ""
;;

Perl

 s{\A\s*|\s*\z}{}gmsx; # remove leading and trailing whitespace

PHP

  $string = trim($string);

Python

Python strings have the strip(), lstrip(), rstrip() methods for removing any character from both ends of a string. If the characters to be removed are not specified then whitespace will be removed. strip() removes from both ends; lstrip() removes leading characters (Left-strip); rstrip() removes trailing characters (Right-strip).

"   xyz   ".strip()            # returns "xyz"
"   xyz   ".lstrip()           # returns "xyz   "
"   xyz   ".rstrip()           # returns "   xyz"
"  x y z  ".replace(' ', '')   # returns "xyz"

Ruby

This is very similar to the python version above.

"    test 1  ".strip            #=> "test 1"
"    test 1  ".lstrip           #=> "test 1  "
"    test 1  ".rstrip           #=> "    test 1"
"    test 1  ".gsub(" ","")     #=> "test1"

Seed7

The trim function removes leading and trailing spaces and control chars:

writeln(trim("  xyz  ")); # writes the string "xyz";

Visual Basic

To remove leading and/or trailing spaces from a string:

    sString = LTrim(sString)          ' Remove leading spaces'
    sString = RTrim(sString)          ' Remove trailing spaces'
    sString = Trim(sString)           ' Remove leading and trailing spaces'

To remove all spaces from a string:

    sString = Replace(sString, " ", "")

Zsh

string="  123 abc xyz  "
${string// /} # output: 123abcxyz