Trim whitespace (spaces) from a string

From CodeCodex

Revision as of 23:27, 8 October 2007 by Tanktop (Talk | contribs)



The String class in Java has a built in trim function: <HIGHLIGHTSYNTAX language="java122">

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



Trim is not built into JavaScript, but you can use prototyping to add this to your code: <HIGHLIGHTSYNTAX language="javascript"> String.prototype.trim = function() {

  return this.replace(/^\s+|\s+$/g,"");

} </HIGHLIGHTSYNTAX> Then you can use this code like this example: <HIGHLIGHTSYNTAX language="javascript"> var input = " xyz "; var output = test.input(); // output = "xyz" </HIGHLIGHTSYNTAX>


<HIGHLIGHTSYNTAX language="perl">

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



<HIGHLIGHTSYNTAX language="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))


Visual Basic=

To remove leading and trailing spaces from a string:

    sString = Trim(sString)

To remove all spaces from a string:

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