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
Why on earth wouldn't you use a regex to remove everything but numbers?
REReplaceNoCase(s,'\D','','ALL')
In Todd's specific case, he wanted to handle "1-2" differently, but outside of that, yes, that would work too.
@andy, @ray: you guys can shave now...the super bowl is over.
I'm not shaving until a certain event happens, which may never happen, so, deal with it. ;)
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.
@ray, hoping to get selected as Saint Nick in the Lafayette Players production of A Christmas Story?
Heh, close...
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
I tried Andy's solution and what used to be giving me
' 3091470'
now gives me
'1083091470'
Ideas?
and val gives me zero.
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.