ColdFusion UDF For Converting Strings Into ASCII Characters

I needed a simple solution for converting strings such as email addresses, etc. into ASCII characters. So, I whipped up this little ColdFusion user-defined function to do just that and wanted to share it with anyone else who might need the same thing one day.

stringToAscii(str)


<cfscript>
function stringToAscii(str) {
    var local = StructNew();
    local.oldStr = '';
    local.newStr = '';
    if ( StructKeyExists(arguments, 'str') and IsSimpleValue(arguments.str) ) {
        local.oldStr = arguments.str;
        for ( local.i=1; local.i lte Len(arguments.str); local.i++ ) {
            local.newStr = local.newStr & '&##' & Asc(Left(local.oldStr,1)) & ';';
            local.oldStr = RemoveChars(local.oldStr,1,1);
        };
    };
    return local.newStr;
};
</cfscript>

Here's some sample code for you to test with:


<cfparam name="form.txt" default="" />
<cfparam name="form.isSubmitted" default="false" />
<cfoutput>
    <form method="post" enctype="application/x-www-form-urlencoded">
        <p><label for="txt">Text:</label><br />
        <input type="text" name="txt" id="txt" size="50" value="#form.txt#" /></p>
        
        <p><input type="submit" value=" Encode It! " /></p>
        <input type="hidden" name="isSubmitted" value="true" />
    </form>
    <cfif form.isSubmitted>
        <h4>#stringToAscii(form.txt)#</h4>
        <cfdump var="#stringToAscii(form.txt)#" /><br />
    </cfif>
</cfoutput>

Enjoy!

Comments

Don't forget to post this to CFLib. (Not that we are caught up.)
# Posted By Raymond Camden | 6/17/10 9:38 AM
@Ray,

Done. Thanks!
# Posted By Steve Withington | 6/17/10 9:46 AM

© 2026, Stephen J. Withington, Jr.  |  Hosted by Hostek.com

Creative Commons License   |   This work is licensed under a Creative Commons Attribution 3.0 Unported License.