View comments | RSS feed

Trim

Description

Removes leading and trailing spaces and control characters from a string.

Returns

A copy of the string parameter, after removing leading and trailing spaces and control characters.

Category

String functions

Function syntax

Trim(string)

See also

LTrim, RTrim

Parameters

Parameter Description

string

A string or a variable that contains a string.

Example

<h3>Trim Example</h3>
<cfif IsDefined("FORM.myText")>
   <cfoutput>
      <pre>
         Your string:   "#FORM.myText#"
         Your string:   "#Trim(FORM.myText)#"
         (trimmed on both sides)
      </pre>
   </cfoutput>
</cfif>
<form method = "post" action = "trim.cfm">
<p>Type in some text, and it will be modified by trim to remove leading 
spaces from the left and right <p><input type = "Text" name = "myText" value = " TEST "> <p><input type = "Submit" name = ""> </form>

ColdFusion 9 | ColdFusion 8 | ColdFusion MX 7 | ColdFusion MX 6.1 | ColdFusion MX | Forums | Developer Center | KnowledgeBase | Bug Reporting

Version 7

Comments


matthewes said on Jun 2, 2005 at 7:10 PM :
"Spaces" seems to be broadly defined. trim() seems to remove at least some non-print characters too, e.g. chr(14). It would be good to know exactly what it does and doesn't trim.
jrunrandy said on Jun 29, 2005 at 12:46 PM :
Good catch! I checked the source code and saw that we just call java.lang.String.trim(), so then I looked at the JavaDocs for the trim method and noticed this note: "... in fact, it trims all ASCII control characters as well."

I entered doc bug 60453.
pablo_s said on Feb 1, 2006 at 8:57 AM :
Additionally, it might be useful to note what characters Trim() does *not* remove. The non-breaking space, chr(160), is not handled by this function. Firefox seems to convert form fields containing this value to normal spaces (chr(32)), but IE6 leaves them as-is.

I created a function, MyTrim, to handle this type of character, but it would be nice to have a more elegant solution:

<cffunction name="MyTrim" returntype="string" output="false">
<cfargument name="s" type="string" required="yes">
<cfreturn Trim(Replace(s, chr(160), " ", "ALL"))>
</cffunction>
Phil Arnold said on May 31, 2006 at 2:05 PM :
Found a freaky error with Trim().

When editing a long string, if you have single apostrophies, after running a Trim(), it doubles it to be two apostrophies.

I've seen this in CFMX6.1 as well as CFMX7.
jon.wolski said on Oct 11, 2006 at 9:46 AM :
The non-breaking space, chr(160), is not a whitespace character, it merely looks like one. There is a bug in the Mozilla core due to a similar misguided assumption (0xA0 is converted to 0x20 in text serialization). cf. https://bugzilla.mozilla.org/show_bug.cgi?id=218277

 

RSS feed | Send me an e-mail when comments are added to this page | Comment Report

Current page: http://livedocs.adobe.com/coldfusion/7/htmldocs/00000656.htm