CFLib.org – Common Function Library Project

replaceSpecialChars(textString[, replaceTheseChars][, replaceWithChar])

Last updated January 04, 2012

author

David Long

Version: 1 | Requires: CF6 | Library: StrLib

Description:
Replaces all special characters in a string of code along with spaces. Code can easily be chaged to exclude spaces.

Return Values:
Returns a string.

Example:

<cfset myString = "!Hello_World! This is my ^string^">
<cfset myNewString = replaceSpecialChars(myString)>
<cfoutput>
    "#myString#" now becomes "#myNewString#"
</cfoutput>

Parameters:

Name Description Required
textString String to have special characters replaced Yes
replaceTheseChars Characters to be replaced No
replaceWithChar Character to replace special characters with. Defaults to chr(0). No

Full UDF Source:

<!---
 Replaces all special characters in a string of text.
 
 @param textString      String to have special characters replaced (Required)
 @param replaceTheseChars      Characters to be replaced (Optional)
 @param replaceWithChar      Character to replace special characters with. Defaults to chr(0). (Optional)
 @return Returns a string. 
 @author David Long (dlong@cagedata.com) 
 @version 1, January 4, 2012 
--->
<cffunction name="replaceSpecialChars" access="public" output="false" returntype="String">
    <cfargument name="textString" type="String" hint="String to have special characters replaced">
    <!--- If you would not like to remove spaces take the number 32 out of the list.--->
    <cfargument name="replaceTheseChars" type="String" default="32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,58,59,60,61,62,63,64,91,92,93,94,95,96,123,124,126" required="false" hint="Characters to be replaced">
    <cfargument name="replaceWithChar" type="String" default="#chr(0)#" required="no" hint="Character to replace special characters with.">
    <cfscript>
        var returnString = ARGUMENTS.textString;
        var i = 1;
        
        for(i=1; i <= listLen(ARGUMENTS.replaceTheseChars,','); i++){
            returnString = replace(returnString,chr(listGetAt(ARGUMENTS.replaceTheseChars,i)),ARGUMENTS.replaceWithChar,'all');
        }
    </cfscript>
    
    <cfreturn returnString />
</cffunction>

Search CFLib.org


Latest Additions

Raymond Camden added
QueryDeleteRows
November 04, 2017

Leigh added
nullPad
May 11, 2016

Raymond Camden added
stripHTML
May 10, 2016

Kevin Cotton added
date2ExcelDate
May 05, 2016

Raymond Camden added
CapFirst
April 25, 2016

Created by Raymond Camden / Design by Justin Johnson