When does ColdFusion's Trim function not trim?

This post is more than 2 years old.

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


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:


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:


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.

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate for HERE Technologies. He focuses on JavaScript, serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

Lafayette, LA https://www.raymondcamden.com