When does ColdFusion's Trim function not trim?

Here is a fun little quiz for you. Given a variable S (a number) that you output to screen with dashes like so:

<cfoutput>-#s#-</cfoutput>

If you see this:

-8 -

then what would you expect to happen after you trim it? If you said 8, than you would be right.... most of the time. Assume you did trim it:

<cfoutput>-#trim(s)#-</cfoutput>

And you still saw a space? What then? My buddy Todd ran into this. The first thing that came to mind was special characters. I suggested looping over every character and printing out the character code like so:

<cfloop index="x" from="1" to="#len(s)#"> <cfset c = mid(s, x, 1)> <cfoutput>#c#=#asc(c)#<br/></cfoutput> </cfloop>

When Todd did this he saw:

8=56
 =160

Yep - a special character. There are a variety of ways to handle this, including the awesomely named deMoronize at CFLib, but in this case Todd needed to strip out not replace the bad character. I would have used a val() but he needed to look out for ranges as well (1-2) and therefore used a isNumeric check beforehand. I know I've blogged about this before but it definitely still trips us all out so watch out for it.

Archived Comments

Comment 1 by andy matthews posted on 2/7/2011 at 9:23 PM

Why on earth wouldn't you use a regex to remove everything but numbers?

REReplaceNoCase(s,'\D','','ALL')

Comment 2 by Raymond Camden posted on 2/7/2011 at 9:30 PM

In Todd's specific case, he wanted to handle "1-2" differently, but outside of that, yes, that would work too.

Comment 3 by JD posted on 2/7/2011 at 10:31 PM

@andy, @ray: you guys can shave now...the super bowl is over.

Comment 4 by Raymond Camden posted on 2/7/2011 at 10:33 PM

I'm not shaving until a certain event happens, which may never happen, so, deal with it. ;)

Comment 5 by SNH posted on 2/8/2011 at 1:24 AM

Character 160 is the non-breaking space, and near universally ignored by trim, rtrim, ltrim, squeeze, and other text commands in a variety of applications. Most of the time have to use a substitute (or replace) command prior to trimming to get it out.

Comment 6 by andy matthews posted on 2/8/2011 at 9:46 AM

@ray, hoping to get selected as Saint Nick in the Lafayette Players production of A Christmas Story?

Comment 7 by Raymond Camden posted on 2/8/2011 at 5:03 PM

Heh, close...

Comment 8 by Larry C. Lyons posted on 2/9/2011 at 1:47 AM

I dunno Ray, you're starting to look like an extra from a Civil War movie. You'd fit right in next summer when they redo the First Battle of Manassas.

larry

Comment 9 by Alejandro Hombrados posted on 1/3/2013 at 1:23 AM

I tried Andy's solution and what used to be giving me
' 3091470'
now gives me
'1083091470'
Ideas?
and val gives me zero.

Comment 10 by Alejandro Hombrados posted on 1/3/2013 at 1:32 AM

Nevermind it was a XMLObject :) coldfusion was just trying to display it as a string. So i thought it was one. sorry for double post.