Trim whitespace (spaces) from a string

From CodeCodex

Contents

[edit] Implementations

[edit] PHP


$string = trim($string);

[edit] Java

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


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

[edit] 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"

[edit] 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" -> ""
;;

[edit] Perl


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

[edit] 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"

[edit] Ruby

This is very similar to the python version above.


irb(main):001:0> test = "    test   "
=> "    test   "
irb(main):002:0> test.strip
=> "test"
irb(main):003:0> test.lstrip
=> "test   "
irb(main):004:0> test.rstrip
=> "    test"

[edit] Seed7

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

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

[edit] 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, " ", "")

[edit] Zsh

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