Removing spaces from a string with coldfusion
Posted by mark at 7:50 PM
6 comments - Categories: Coldfusion
Ran into this problem today and it seemed to take quite a long time for me to find a solution so I'm posting how it works here for the benefit of others. This method uses a regular expression to do it's bidding.
<!--- set up a test variable --->
<cfset mySpaceFilledString = "a brand new combine harvester" />
<!--- remove ALL spaces from the string --->
<cfset mySpaceFreeVariable = ReReplace(mySpaceFilledString, "[[:space:]]","","ALL")>
<!--- check it works --->
<cfdump var = #mySpaceFreeVariable#>
this returns "abrandnewcombineharvester" - all spaces removed from the whole string
To simply remove the spaces at the beginning and end of a string (a form field for example) it's much easier...
<!--- set up a test variable --->
<cfset form.myTestString = " mark mcaulay " />
<!--- remove spaces from start and end of the string --->
<cfset mySpaceFreeVariable = Trim(form.myTestString)>
<!--- check it works --->
<cfdump var = #mySpaceFreeVariable#>
this returns "mark mcaulay" - only the spaces at the start and end of the string have been removed
Hope this helps someone!
ᅠ
**UPDATE - Just for good measure, and of course, to keep James happy ;) here is the equivelent in php
<?php
// set up a test variable
$mySpaceFilledString = " a brand new combine harvester ";
// remove all spaces from the string
$mySpaceFreeVariable = str_replace(" ", "", $mySpaceFilledString);
// check it works
echo $mySpaceFreeVariable;
?>
this returns "abrandnewcombineharvester" - all spaces removed from the whole string
ᅠ
To simply remove the spaces at the beginning and end of a string (a form field for example) it's again, much easier...
<?php
// set up a test variable
$myFormVariable = " mark mcaulay ";
// remove spaces from start and end of the string
$myTrimmedVariable = trim($mySpaceFilledString);
//check it works
echo $myTrimmedVariable;
?>
this returns "mark mcaulay" - only the spaces at the start and end of the string have been removed
ᅠ



James Buckingham wrote on 07/18/08 9:47 AM
What would be really good to see from you Mark is a comparison of your experiences with PHP and ColdFusion.Even something as simple as building and outputting a query hopefully will demostrate how easy it is to learn/use CF.
In fact bugger it. It's so easy I'll write it in here :-).
1) Create a query
<cfquery name="getUsers" datasource="myDatabase">
select name,email,telno
from user
</cfquery>
2) Output into a list
<ul>
<cfoutput query="getUsers">
<li>#name#</li>
<li>#email#</li>
<li>#telno#</li>
</cfoutput>
</ul>
-----
Now correct me if I'm wrong but can PHP/ASP do that as easily? :-)