Put all this code in stringer.cfm.
<cfparam name="form.MyString" default=""> <cfparam name="form.Demo" default=""> <form action="stringer.cfm" method="post"> Enter a string; include spaces before, inside, and after.<br> Check the box if you want a surprise.<br> <input type="string" name="MyString" value=<cfoutput>"#form.MyString#"</cfoutput>> <cfif Demo is "on"> <cfset Show="checked"> <cfelse> <cfset Show=""> </cfif> <input type="checkbox" name="Demo" <cfoutput>#Show#</cfoutput>> <input type="submit" name="Dummy" value="OK"> </form>
<cfscript>
function countSpace(InString) {
if (len(trim(InString)) lt 1) {
return 0;
}
Nr=0;
StrLen=len(InString);
// Can you find a leak?
for (i=1; i le StrLen; i=i+1) {
Spot=mid(InString,i,1);
if (Spot is ' ') {
Nr=Nr+1;
}
}
return Nr;
}
function clipTrim(InString, DesiredLength) {
if (len(trim(InString)) lt 1) {
return "";
}
if (len(trim(InString)) le DesiredLength) {
return trim(InString);
}
return left(trim(InString), DesiredLength);
}
I find this function less useful. It clips the string but doesn't trim it first; so, the results are not what you might expect. Again, deal with empty input first, then with normal input.
function clip(InString, DesiredLength) {
if (len(InString) lt 1) {
return "";
}
if (len(InString) le DesiredLength) {
return InString;
}
return left(InString, DesiredLength);
}
function sideEffect(Mode) {
if (Mode is "on") {
return "countSpace loop value leaked! It's "&i;
}
else {
return '';
}
}
</cfscript>
<cfoutput>countSpace sees #countSpace(form.MyString)# spaces</cfoutput> <p> With a desired length of 5...<br> <cfoutput> <pre> clipTrim says: [#clipTrim(form.MyString,5)#] clip says: [#clip(form.MyString,5)#] </pre> </cfoutput> <p> With a desired length of 20...<br> <cfoutput> <pre> clipTrim says: [#clipTrim(form.MyString,20)#] clip says: [#clip(form.MyString,20)#] <p> #sideEffect(form.Demo)# </cfoutput> </pre>
Somehow, the loop counter has become available to all functions on the page.
The variables declared in a user-defined function are available to other user-defined functions unless you say something like "var i=0;" before the other statements in the function. In a reversal from some languages, saying "var" makes the variable local to a single function. Saying nothing, even for a loop variable, makes it global to all the user-defined functions in the same page request.
This result was unexpected, but if you're careful, user-defined functions can simplify your life. =Marty=