Parameter
- CFML Reference User Guide
- ColdFusion functions
- ColdFusion functions by category
- Functions a-b
- Abs
- ACos
- AddSOAPRequestHeader
- AddSOAPResponseHeader
- AjaxLink
- AjaxOnLoad
- ApplicationStop
- ArrayAppend
- ArrayAvg
- ArrayClear
- ArrayContains
- ArrayContainsNoCase
- ArrayDelete
- ArrayDeleteAt
- ArrayDeleteNoCase
- ArrayEach
- ArrayFilter
- ArrayFind
- ArrayFindAll
- ArrayFindAllNoCase
- ArrayFindNoCase
- ArrayInsertAt
- ArrayIsDefined
- ArrayIsEmpty
- ArrayLen
- ArrayMap
- ArrayMax
- ArrayMin
- ArrayNew
- ArrayPrepend
- ArrayReduce
- ArrayResize
- ArraySet
- ArraySetMetadata
- ArraySlice
- ArraySort
- ArraySum
- ArraySwap
- ArrayToList
- Asc
- ASin
- Atn
- AuthenticatedContext
- AuthenticatedUser
- BinaryDecode
- BinaryEncode
- BitAnd
- BitMaskClear
- BitMaskRead
- BitMaskSet
- BitNot
- BitOr
- BitSHLN
- BitSHRN
- BitXor
- BooleanFormat
- Abs
- Functions-c-d
- CacheGet
- CacheGetAllIds
- CacheGetMetadata
- CacheGetProperties
- CacheGetSession
- CacheIdExists
- CachePut
- CacheRegionExists
- CacheRegionNew
- CacheRegionRemove
- CacheRemove
- CacheRemoveAll
- CacheSetProperties
- CallStackDump
- CallStackGet
- CanDeSerialize
- Canonicalize
- CanSerialize
- Ceiling
- CharsetDecode
- CharsetEncode
- Chr
- CJustify
- Compare
- CompareNoCase
- Cos
- CreateDate
- CreateDateTime
- CreateObject
- CreateObject: .NET object
- CreateObject: COM object
- CreateObject: component object
- CreateObject: CORBA object
- CreateObject: Java or EJB object
- CreateObject: web service object
- CreateODBCDate
- CreateODBCDateTime
- CreateODBCTime
- CreateSignedJWT
- CreateEncryptedJWT
- CreateTime
- CreateTimeSpan
- CreateUUID
- CSRFGenerateToken
- CSRFVerifyToken
- CSVRead
- CSVWrite
- CSVProcess
- DateAdd
- DateCompare
- DateConvert
- DateDiff
- DateFormat
- DatePart
- DateTimeFormat
- Day
- DayOfWeek
- DayOfWeekAsString
- DayOfYear
- DaysInMonth
- DaysInYear
- DE
- DecimalFormat
- DecodeForHTML
- DecodeFromURL
- DecrementValue
- Decrypt
- DecryptBinary
- DeleteClientVariable
- Deserialize
- DeserializeJSON
- DeserializeXML
- DirectoryCopy
- DirectoryCreate
- DirectoryDelete
- DirectoryExists
- DirectoryList
- DirectoryRename
- DollarFormat
- DotNetToCFType
- Duplicate
- Functions-e-g
- EncodeForCSS
- EncodeForDN
- EncodeForHTML
- EncodeForHTMLAttribute
- EncodeForJavaScript
- EncodeForLDAP
- EncodeForURL
- EncodeForXML
- EncodeForXMLAttribute
- EncodeForXpath
- Encrypt
- EncryptBinary
- EntityDelete
- EntityLoad
- EntityLoadByExample
- EntityLoadByPK
- EntityMerge
- EntityNew
- EntityReload
- EntitySave
- EntityToQuery
- Evaluate
- Exp
- ExpandPath
- FileClose
- FileCopy
- FileDelete
- FileExists
- FileGetMimeType
- FileIsEOF
- FileMove
- FileOpen
- FileRead
- FileReadBinary
- FileReadLine
- FileSeek
- FileSetAccessMode
- FileSetAttribute
- FileSetLastModified
- FileSkipBytes
- FileUpload
- FileUploadAll
- FileWrite
- FileWriteLine
- Find
- FindNoCase
- FindOneOf
- FirstDayOfMonth
- Fix
- Floor
- FormatBaseN
- GeneratePBKDFKey
- GenerateSecretKey
- GetApplicationMetadata
- GetAuthUser
- GetBaseTagData
- GetBaseTagList
- GetBaseTemplatePath
- GetClientVariablesList
- GetComponentMetaData
- GetContextRoot
- GetCPUUsage
- GetCurrentTemplatePath
- GetCSPNonce
- GetDirectoryFromPath
- GetEncoding
- GetException
- GetFileFromPath
- GetFileInfo
- GetFreeSpace
- GetFunctionCalledName
- GetFunctionList
- GetGatewayHelper
- GetHttpRequestData
- GetHttpTimeString
- GetK2ServerDocCount
- GetK2ServerDocCountLimit
- GetLocale
- GetLocaleDisplayName
- GetLocalHostIP
- GetMetaData
- GetMetricData
- GetPageContext
- GetPropertyString
- GetPropertyFile
- GetPrinterInfo
- GetPrinterList
- GetProfileSections
- GetProfileString
- GetReadableImageFormats
- GetSafeHTML
- GetSAMLAuthRequest
- GetSAMLLogoutRequest
- Generate3DesKey
- GenerateSAMLSPMetadata
- GetSOAPRequest
- GetSOAPRequestHeader
- GetSOAPResponse
- GetSOAPResponseHeader
- GetSystemFreeMemory
- GetSystemTotalMemory
- GetTempDirectory
- GetTempFile
- GetTemplatePath
- GetTickCount
- GetTimeZoneInfo
- GetToken
- GetTotalSpace
- GetUserRoles
- GetVFSMetaData
- GetWriteableImageFormats
- Functions-h-im
- Hash
- HMac
- Hour
- HQLMethods
- HTMLCodeFormat
- HTMLEditFormat
- IIf
- ImageAddBorder
- ImageBlur
- ImageClearRect
- ImageCopy
- ImageCreateCaptcha
- ImageCrop
- ImageDrawArc
- ImageDrawBeveledRect
- ImageDrawCubicCurve
- ImageDrawLine
- ImageDrawLines
- ImageDrawOval
- ImageDrawPoint
- ImageDrawQuadraticCurve
- ImageDrawRect
- ImageDrawRoundRect
- ImageDrawText
- ImageFlip
- ImageGetBlob
- ImageGetBufferedImage
- ImageGetEXIFMetadata
- ImageGetEXIFTag
- ImageGetHeight
- ImageGetIPTCMetadata
- ImageGetIPTCTag
- ImageGetMetadata
- ImageGetWidth
- ImageGrayscale
- ImageInfo
- ImageMakeColorTransparent
- ImageMakeTranslucent
- ImageNegative
- ImageNew
- ImageOverlay
- ImagePaste
- ImageRead
- ImageReadBase64
- ImageResize
- ImageRotate
- ImageRotateDrawingAxis
- ImageScaleToFit
- ImageSetAntialiasing
- ImageSetBackgroundColor
- ImageSetDrawingColor
- ImageSetDrawingStroke
- ImageSetDrawingTransparency
- ImageSharpen
- ImageShear
- ImageShearDrawingAxis
- ImageTranslate
- ImageTranslateDrawingAxis
- ImageWrite
- ImageWriteBase64
- ImageXORDrawingMode
- Functions-in-k
- IncrementValue
- InputBaseN
- Insert
- Int
- InterruptThread
- InvalidateOauthAccesstoken
- Invoke
- InitSAMLAuthRequest
- InitSAMLLogoutRequest
- InvokeCFClientFunction
- IsArray
- IsAuthenticated
- IsAuthorized
- IsBinary
- IsBoolean
- IsClosure
- IsCustomFunction
- IsDate
- IsDateObject
- IsDDX
- IsDebugMode
- IsDefined
- IsImage
- IsImageFile
- IsInstanceOf
- IsIPv6
- IsJSON
- IsK2ServerABroker
- IsK2ServerDocCountExceeded
- IsK2ServerOnline
- IsLeapYear
- IsLocalHost
- IsNull
- IsNumeric
- IsNumericDate
- IsObject
- isOnline
- IsPDFArchive
- IsPDFFile
- IsPDFObject
- IsProtected
- IsQuery
- isSamlLogoutResponse
- isSafeHTML
- IsSimpleValue
- IsSOAPRequest
- IsSpreadsheetFile
- IsSpreadsheetObject
- IsStruct
- isThreadInterrupted
- IsUserInAnyRole
- IsUserInRole
- IsUserLoggedIn
- IsValid
- IsValidOauthAccesstoken
- IsWDDX
- IsXML
- IsXmlAttribute
- IsXmlDoc
- IsXmlElem
- IsXmlNode
- IsXmlRoot
- JavaCast
- JSStringFormat
- Functions-l
- LCase
- Left
- Len
- ListAppend
- ListChangeDelims
- ListContains
- ListContainsNoCase
- ListDeleteAt
- ListEach
- ListFilter
- ListFind
- ListFindNoCase
- ListFirst
- ListGetAt
- ListGetDuplicates
- ListInsertAt
- ListLast
- ListLen
- ListMap
- ListPrepend
- ListQualify
- ListReduce
- ListRemoveDuplicates
- ListRest
- ListSetAt
- ListSort
- ListToArray
- ListValueCount
- ListValueCountNoCase
- LJustify
- Location
- Log
- Log10
- LSCurrencyFormat
- LSDateFormat
- LSDateTimeFormat
- LSEuroCurrencyFormat
- LSIsCurrency
- LSIsDate
- LSIsNumeric
- LSNumberFormat
- LSParseCurrency
- LSParseDateTime
- LSParseEuroCurrency
- LSParseNumber
- LSTimeFormat
- LTrim
- Functions-m-r
- Max
- Mid
- Min
- Minute
- Month
- MonthAsString
- Now
- NumberFormat
- ObjectEquals
- ObjectLoad
- ObjectSave
- OnWSAuthenticate
- ORMClearSession
- ORMCloseAllSessions
- ORMCloseSession
- ORMEvictCollection
- ORMEvictEntity
- ORMEvictQueries
- ORMExecuteQuery
- ORMFlush
- ORMFlushall
- ORMGetSession
- ORMGetSessionFactory
- ORMIndex
- ORMIndexPurge
- ORMReload
- ORMSearch
- ORMSearchOffline
- ParagraphFormat
- ParameterExists
- ParseDateTime
- Pi
- PrecisionEvaluate
- ProcessSAMLResponse
- ProcessSAMLLogoutRequest
- Quarter
- PreserveSingleQuotes
- QueryAddColumn
- QueryAddRow
- QueryConvertForGrid
- QueryExecute
- QueryFilter
- QueryGetResult
- QueryGetRow
- QueryKeyExists
- QueryMap
- QueryNew
- QueryReduce
- QuerySetCell
- QuotedValueList
- QueryEach
- Rand
- Randomize
- RandRange
- ReEscape
- REFind
- REFindNoCase
- ReleaseComObject
- REMatch
- REMatchNoCase
- RemoveCachedQuery
- RemoveChars
- RepeatString
- Replace
- ReplaceList
- ReplaceNoCase
- REReplace
- REReplaceNoCase
- RestDeleteApplication
- RestSetResponse
- RestInitApplication
- Reverse
- Right
- RJustify
- Round
- RTrim
- Functions-s
- Second
- SendGatewayMessage
- SendSAMLLogoutResponse
- Serialize
- SerializeJSON
- SerializeXML
- SessionInvalidate
- SessionRotate
- SessionGetMetaData
- SessionInvalidate
- SessionRotate
- SetDay
- SetEncoding
- SetHour
- SetLocale
- SetMonth
- SetProfileString
- SetPropertyString
- SetVariable
- SetYear
- Sgn
- Sin
- Sleep
- SpanExcluding
- SpanIncluding
- SpreadsheetAddAutoFilter
- SpreadsheetAddColumn
- SpreadsheetAddFreezePane
- SpreadsheetAddImage
- SpreadsheetAddInfo
- SpreadsheetAddPageBreaks
- SpreadsheetAddRow
- SpreadsheetAddRows
- SpreadsheetAddSplitPane
- SpreadsheetCreateSheet
- SpreadsheetDeleteColumn
- SpreadsheetDeleteColumns
- SpreadsheetDeleteRow
- SpreadsheetDeleteRows
- SpreadsheetFormatCell
- SpreadsheetFormatColumn
- SpreadsheetFormatCellRange
- SpreadsheetFormatColumn
- SpreadsheetFormatColumns
- SpreadsheetFormatRow
- SpreadsheetFormatRows
- SpreadsheetGetCellComment
- SpreadsheetGetCellFormula
- SpreadsheetGetCellValue
- SpreadsheetGetColumnCount
- SpreadsheetInfo
- SpreadsheetMergeCells
- SpreadsheetNew
- SpreadsheetRead
- SpreadsheetReadBinary
- SpreadsheetRemoveSheet
- SpreadsheetSetActiveSheet
- SpreadsheetSetActiveSheetNumber
- SpreadsheetSetCellComment
- SpreadsheetSetCellFormula
- SpreadsheetSetCellValue
- SpreadsheetSetColumnWidth
- SpreadsheetSetFooter
- SpreadsheetSetHeader
- SpreadsheetSetRowHeight
- SpreadsheetShiftColumns
- SpreadsheetShiftRows
- SpreadsheetWrite
- StreamingSpreadsheetNew
- StreamingSpreadsheetCleanup
- StreamingSpreadsheetRead
- StreamingSpreadsheetProcess
- SpreadsheetSetFooterImage
- SpreadsheetSetHeaderImage
- SpreadsheetSetFittoPage
- SpreadsheetUngroupColumns
- SpreadsheetGroupColumns
- SpreadsheetUngroupRows
- SpreadsheetGroupRows
- SpreadsheetRemoveColumnBreak
- SpreadsheetSetColumnBreak
- SpreadsheetRemoveRowBreak
- SpreadsheetSetRowBreak
- SpreadsheetRemovePrintGridlines
- SpreadsheetAddPrintGridlines
- SpreadsheetGetColumnWidth
- SpreadsheetSetColumnHidden
- SpreadsheetSetRowHidden
- SpreadsheetisColumnHidden
- SpreadsheetisRowHidden
- SpreadsheetisStreamingXmlFormat
- SpreadsheetisXmlFormat
- SpreadsheetisBinaryFormat
- SpreadsheetRenameSheet
- SpreadsheetRemoveSheetNumber
- SpreadsheetGetLastRowNumber
- SpreadsheetGetPrintOrientation
- Sqr
- StripCR
- StructAppend
- StructClear
- StructCopy
- StructCount
- StructDelete
- StructEach
- StructFilter
- StructFind
- StructFindKey
- StructFindValue
- StructGet
- StructGetMetadata
- StructInsert
- StructIsEmpty
- StructKeyArray
- StructKeyExists
- StructKeyList
- StructMap
- StructNew
- StructReduce
- StructSetMetadata
- StructSort
- StructToSorted
- StructUpdate
- StructValueArray
- StoreSetMetadata
- StoreGetACL
- StoreGetMetadata
- StoreAddACL
- StoreSetACL
- Functions-t-z
- Tan
- ThreadJoin
- ThreadTerminate
- Throw
- TimeFormat
- ToBase64
- ToBinary
- ToScript
- ToString
- Trace
- Transactionandconcurrency
- TransactionCommit
- TransactionRollback
- TransactionSetSavePoint
- Trim
- UCase
- URLDecode
- URLEncodedFormat
- URLSessionFormat
- Val
- ValueList
- VerifyClient
- Week
- Wrap
- WriteDump
- WriteLog
- WriteOutput
- WSGetAllChannels
- WSGetSubscribers
- WSPublish
- WSSendMessage
- XmlChildPos
- XmlElemNew
- XmlFormat
- XmlGetNodeType
- XmlNew
- XmlParse
- XmlSearch
- XmlTransform
- XmlValidate
- Year
- YesNoFormat
- ColdFusion tags
- ColdFusion tag summary
- ColdFusion tags by category
- Application framework tags
- Communications tags
- Database manipulation tags
- Data output tags
- Debugging tags
- Exception handling tags
- Extensibility tags
- File management tags
- Flow-control tags
- Forms tags
- Internet Protocol tags
- Page processing tags
- Security tags
- Variable manipulation tags
- Other tags
- Tags a-b
- Tags c
- cfcache
- cfcalendar
- cfcase
- cfcatch
- cfchart
- cfchart tag in ColdFusion
- Get started with cfchart
- Customize a chart using cfchart
- Advanced cfchart customization options
- Create an area chart in ColdFusion
- Create line charts in ColdFusion
- Create bar charts in ColdFusion
- Create floating bar charts in ColdFusion
- Create histograms in ColdFusion
- Create pie charts in ColdFusion
- Create funnel charts in ColdFusion
- Create pyramid charts in ColdFusion
- Create curve charts in ColdFusion
- Create boxplots in ColdFusion
- Create donut charts in ColdFusion
- Create bubble charts in ColdFusion
- Create scatterplots in ColdFusion
- Create radar charts in ColdFusion
- Other chart types in ColdFusion (Cone, Cylinder, Piano, and Bullet)
- Advanced customization options in cfchart
- cfchartdata
- cfchartseries
- cfchartset
- cfclient
- cfclientsettings
- cfcol
- cfcollection
- cfcomponent
- cfcontent
- cfcontinue
- cfcookie
- Tags f
- cffeed
- cffile
- cffile action = "append"
- cffile action = "copy"
- cffile action = "delete"
- cffile action = "move"
- cffile action = "read"
- cffile action = "readBinary"
- cffile action = "rename"
- cffile action = "upload"
- cffile action = "uploadAll"
- cffile action = "write"
- cffileupload
- cffinally
- cfflush
- cfform
- cfformgroup
- cfformitem
- cfftp
- cfftp: Connection: file and directory operations
- cfftp: Opening and closing FTP server connections
- cfftp : Opening and closing secure FTP server connections
- cfftp action = "listDir"
- cffunction
- Tags g-h
- Tags i
- Tags j-l
- cfjava
- cflayout
- cflayoutarea
- cfldap
- cflocation
- cflock
- cflog
- cflogin
- cfloginuser
- cflogout
- cfloop
- cfloop : conditional loop
- cfloop : index loop
- cfloop : looping over a COM collection or structure
- cfloop : looping over a date or time range
- cfloop : looping over a list, a file, or an array
- cfloop : looping over a query
- Tags m-o
- cfmail
- cfmailparam
- cfmailpart
- cfmap
- cfmapitem
- cfmediaplayer
- cfmenu
- cfmenuitem
- cfmessagebox
- cfmodule
- cfNTauthenticate
- cfoauth
- cfobject
- cfobject: .NET object
- cfobject: COM object
- cfobject: component object
- cfobject: CORBA object
- cfobject: Java or EJB object
- cfobject: web service object
- cfobjectcache
- cfoutput
- Tags p-q
- Tags r-s
- Tags t
- Tags u-z
- CFML Reference
- Reserved words and variables
- Ajax JavaScript functions
- Ajax JavaScript functions
- Function summary Ajax
- ColdFusion.Ajax.submitForm
- ColdFusion.Autosuggest.getAutosuggestObject
- ColdFusion.Layout.enableSourceBind
- ColdFusion.MessageBox.getMessageBoxObject
- ColdFusion.ProgressBar.getProgressBarObject
- ColdFusion.MessageBox.isMessageBoxDefined
- JavaScriptFunctionsinColdFusion9Update1
- ColdFusion ActionScript functions
- ColdFusion mobile functions
- Application.cfc reference
- Script functions implemented as CFCs
- ColdFusion Flash Form style reference
- Styles valid for all controls
- Styles for cfform
- Styles for cfformgroup with horizontal or vertical type attributes
- Styles for box-style cfformgroup elements
- Styles for cfformgroup with accordion type attribute
- Styles for cfformgroup with tabnavigator type attribute
- Styles for cfformitem with hrule or vrule type attributes
- Styles for cfinput with radio, checkbox, button, image, or submit type attributes
- Styles for cftextarea tag and cfinput with text, password, or hidden type attributes
- Styles for cfselect with size attribute value of 1
- Styles for cfselect with size attribute value greater than 1
- Styles for cfcalendar tag and cfinput with dateField type attribute
- Styles for the cfgrid tag
- Styles for the cftree tag
- ColdFusion Flash Form Style Reference
- ColdFusion event gateway reference
- ColdFusion Event Gateway reference
- addEvent
- CFEvent
- CFEventclass
- Constructor
- Gateway development interfaces and classes
- getStatus
- setCFCPath
- setCFCMethod
- getOriginatorID
- getLogger
- getBuddyList
- getBuddyInfo
- IM gateway message sending commands
- IM Gateway GatewayHelper class methods
- onIncomingMessage
- onIMServerMessage
- onBuddyStatus
- onAddBuddyResponse
- onAddBuddyRequest
- IM Gateway CFC incoming message methods
- IM gateway methods and commands
- CFML CFEvent structure
- warn
- info
- setOriginatorID
- data command
- submit Multi command
- submit command
- setGatewayType
- setGatewayID
- setData
- setCFCListeners
- outgoingMessage
- getStatusTimeStamp
- numberOfMessagesReceived
- numberOfMessagesSent
- removeBuddy
- removeDeny
- removePermit
- setNickName
- setPermitMode
- setStatus
- SMS Gateway CFEvent structure and commands
- SMS Gateway incoming message CFEvent structure
- getStatusAsString
- getProtocolName
- getPermitMode
- getPermitList
- getNickName
- getName
- getDenyList
- getCustomAwayMessage
- getQueueSize
- getMaxQueueSize
- getHelper
- getGatewayType
- getGatewayServices
- getGatewayID_1
- getGatewayID
- getData
- getCFCTimeout
- setCFCTimeout
- getCFCPath
- getCFCMethod
- GatewayServices class
- Gateway interface
- GatewayHelper interface
- addPermit
- addDeny
- addBuddy
- error
- debug
- Logger class
- stop
- start
- CFML event gateway SendGatewayMessage data parameter
- restart
- fatal
- SMS gateway message sending commands
- ColdFusion C++ CFX Reference
- ColdFusion Java CFX reference
- WDDX JavaScript Objects
- Cloud services
- ColdFusion and GCP Storage
- ColdFusion and GCP Firestore
- ColdFusion and GCP PubSub
- ColdFusion and Amazon S3
- ColdFusion and DynamoDB
- ColdFusion and Amazon SQS
- ColdFusion and Amazon SNS
- ColdFusion and MongoDB
- ColdFusion and Azure Blob
- ColdFusion and Azure Service Bus
- Multi-cloud storage services
- Multi-cloud RDS databases
- ColdFusion and Azure Cosmos DB
Description
Replaces occurrences of a string in a given string with either another string or the result of a callback function. Replaces the first occurrence by default, or can replace all. The search is case-sensitive. See ReplaceNoCase to perform case-insensitive searching.
Returns
The string, after making replacements.
Category
Function syntax
Replace(string, searchstring, replacestring|obj [, scope ][,start])
History
ColdFusion (2021 release):
- Added the parameter start.
- Also, callback support is added.
See also
Parameters
|
|
Description |
|
string |
A string or a variable that contains one. String in which to search. |
|
searchstring |
A string or a variable that contains one. String to search. |
|
obj |
Replacement string (or a variable that contains one) or a callback function that returns the replacement string. You can pass the callback function in this argument. function(transform,position,original) {...} |
|
scope |
|
|
start |
Position to start searching in the string (defaults to 1). |
Usage
To remove a string, specify the empty string ("") as substring2. You do not need to escape comma characters in strings. For example, the following code deletes the commas from the sentence:
replace("The quick brown fox jumped over the lazy cow, dog, and cat.",",","","All") |
Example
<cfoutput>#replace("The quick brown fox","o","cf","all")#</cfoutput>
The code produces the following output:
The quick brcfwn fcfx
Example 1
Example with callback function
<cfscript>
myStr="The quick brown fox jumped over the brown dog";
outStr = replace( myStr, "brown", function (transform, position, original){
return UCase(transform);
}, "all");
writeoutput(outStr);
</cfscript>
Output
The quick BROWN fox jumped over the BROWN dog
Example 2
<cfscript>
// Define the callback function
callback=(regexp,position,original)=>{
retString = regExp.reverse()&"aze"
return retString
}
baseStr="The quick brown fox jumped over the lazy cow."
writeOutput(replace(baseStr, "ow", callback, "all", len("The quick bro")) & "<br>")
writeOutput(replace(baseStr, "ow", callback, "all", len("The quick brown")) & "<br>")
</cfscript>
Output
The quick brwoazen fox jumped over the lazy cwoaze.
The quick brown fox jumped over the lazy cwoaze.
Usage
To remove a string, specify the empty string ("") as substring2. You do not need to escape comma characters in strings. For example, the following code deletes the commas from the sentence:
replace("The quick brown fox jumped over the lazy cow, dog, and cat.",",","","All") |
Example
<cfoutput>
#replace("The quick brown fox","fox","dog")#
</cfoutput>
The code produces the following output:
The quick brown dog
Example- usage of "all"
<cfoutput>
#replace("The quick brown fox jumped over the brown dog","brown","black")#
</cfoutput>
Output
The quick black fox jumped over the brown dog
You can't use this replace to change "the" to "a" because replace is case-sensitive.
Real-world use cases of the Replace function
Data sanitization and cleaning
Clean and sanitize user input data for storage and display. Remove unwanted characters, normalize data formats, and ensure data consistency.
<cfscript>
writeOutput("<h2>1. Data Sanitization & Cleansing</h2>");
// Sample user input data that needs cleaning
userInputs = [
{field: "Phone Number", rawData: "(555) 123-4567 ext. 890", description: "Remove formatting for storage"},
{field: "Social Security", rawData: "123-45-6789", description: "Remove dashes for database storage"},
{field: "Credit Card", rawData: "4111-1111-1111-1111", description: "Remove dashes and spaces"},
{field: "ZIP Code", rawData: "12345-6789", description: "Extract 5-digit ZIP"},
{field: "User Comment", rawData: "This is <script>alert('hack')</script> great!", description: "Remove dangerous HTML/JS"}
];
writeOutput("<h3>Input Data Sanitization Examples</h3>");
writeOutput("<table border='1' cellpadding='8'>");
writeOutput("<tr><th>Field Type</th><th>Raw Input</th><th>Sanitized Output</th><th>Method Used</th><th>Business Purpose</th></tr>");
for (input in userInputs) {
sanitizedData = "";
method = "";
switch (input.field) {
case "Phone Number":
// Remove all non-numeric characters for storage
sanitizedData = replace(input.rawData, "(", "", "all");
sanitizedData = replace(sanitizedData, ")", "", "all");
sanitizedData = replace(sanitizedData, "-", "", "all");
sanitizedData = replace(sanitizedData, " ", "", "all");
sanitizedData = replace(sanitizedData, "ext.", "", "all");
method = "Multiple Replace calls to remove formatting";
break;
case "Social Security":
// Remove dashes for database storage
sanitizedData = replace(input.rawData, "-", "", "all");
method = "Replace dashes with empty string";
break;
case "Credit Card":
// Remove dashes and spaces, keep only numbers
sanitizedData = replace(input.rawData, "-", "", "all");
sanitizedData = replace(sanitizedData, " ", "", "all");
method = "Remove separators for secure storage";
break;
case "ZIP Code":
// Extract 5-digit ZIP (remove extended part)
if (find("-", input.rawData)) {
sanitizedData = left(input.rawData, find("-", input.rawData) - 1);
} else {
sanitizedData = input.rawData;
}
method = "Extract base ZIP code";
break;
case "User Comment":
// Remove dangerous HTML/JavaScript tags
sanitizedData = replace(input.rawData, "<script>", "", "all");
sanitizedData = replace(sanitizedData, "</script>", "", "all");
sanitizedData = replace(sanitizedData, "<", "<", "all");
sanitizedData = replace(sanitizedData, ">", ">", "all");
method = "XSS prevention via HTML encoding";
break;
}
writeOutput("<tr>");
writeOutput("<td><strong>" & input.field & "</strong></td>");
writeOutput("<td>" & encodeForHTML(input.rawData) & "</td>");
writeOutput("<td><strong>" & encodeForHTML(sanitizedData) & "</strong></td>");
writeOutput("<td>" & method & "</td>");
writeOutput("<td>" & input.description & "</td>");
writeOutput("</tr>");
}
writeOutput("</table><br>");
// Advanced sanitization with callback functions (ColdFusion 2021+)
writeOutput("<h3>Advanced Sanitization with Callback Functions</h3>");
// Example: Normalize phone numbers using callback
phoneNumbers = ["(555) 123-4567", "555.123.4567", "555 123 4567", "+1-555-123-4567"];
writeOutput("<table border='1' cellpadding='8'>");
writeOutput("<tr><th>Original Phone</th><th>Normalized Phone</th><th>Formatted Display</th></tr>");
for (phone in phoneNumbers) {
// First clean the phone number
cleanPhone = replace(phone, "(", "", "all");
cleanPhone = replace(cleanPhone, ")", "", "all");
cleanPhone = replace(cleanPhone, "-", "", "all");
cleanPhone = replace(cleanPhone, ".", "", "all");
cleanPhone = replace(cleanPhone, " ", "", "all");
cleanPhone = replace(cleanPhone, "+1", "", "all");
// Format for display
if (len(cleanPhone) == 10) {
formattedPhone = "(" & left(cleanPhone, 3) & ") " &
mid(cleanPhone, 4, 3) & "-" &
right(cleanPhone, 4);
} else {
formattedPhone = cleanPhone;
}
writeOutput("<tr>");
writeOutput("<td>" & phone & "</td>");
writeOutput("<td>" & cleanPhone & "</td>");
writeOutput("<td><strong>" & formattedPhone & "</strong></td>");
writeOutput("</tr>");
}
writeOutput("</table><br>");
</cfscript>
Simple templates
Replace placeholders in templates with real data.
<cfscript>
writeOutput("<hr><h2>2. Simple Templates</h2>");
// Example 1: Simple email template
emailTemplate = "Hello {{NAME}}, your order total is ${{AMOUNT}}. Thank you!";
// Replace placeholders with actual data
customerName = "John Smith";
orderAmount = "25.99";
personalizedEmail = replace(emailTemplate, "{{NAME}}", customerName, "all");
personalizedEmail = replace(personalizedEmail, "{{AMOUNT}}", orderAmount, "all");
writeOutput("<h3>Email Template Example</h3>");
writeOutput("<p><strong>Template:</strong> " & emailTemplate & "</p>");
writeOutput("<p><strong>Result:</strong> " & personalizedEmail & "</p><br>");
// Example 2: Simple form letter
letter = "Dear {{TITLE}} {{LASTNAME}}, your appointment is on {{DATE}} at {{TIME}}.";
title = "Mr.";
lastName = "Johnson";
appointmentDate = "March 15, 2024";
appointmentTime = "2:00 PM";
finalLetter = replace(letter, "{{TITLE}}", title, "all");
finalLetter = replace(finalLetter, "{{LASTNAME}}", lastName, "all");
finalLetter = replace(finalLetter, "{{DATE}}", appointmentDate, "all");
finalLetter = replace(finalLetter, "{{TIME}}", appointmentTime, "all");
writeOutput("<h3>Form Letter Example</h3>");
writeOutput("<p><strong>Template:</strong> " & letter & "</p>");
writeOutput("<p><strong>Result:</strong> " & finalLetter & "</p><br>");
// Example 3: Simple HTML template
htmlTemplate = "<h1>Welcome {{USER}}!</h1><p>You have {{COUNT}} new messages.</p>";
userName = "Sarah";
messageCount = "3";
finalHTML = replace(htmlTemplate, "{{USER}}", userName, "all");
finalHTML = replace(finalHTML, "{{COUNT}}", messageCount, "all");
writeOutput("<h3>HTML Template Example</h3>");
writeOutput("<p><strong>Template:</strong> " & encodeforHTML(htmlTemplate) & "</p>");
writeOutput("<p><strong>Result:</strong> " & finalHTML & "</p>");
</cfscript>
Cleaning up text
Remove unwanted characters and fix formatting.
<cfscript>
writeOutput("<hr><h2>3. Cleaning Up Text</h2>");
// Example 1: Fix URLs with double slashes
messyURL = "https://example.com//products//items//details/";
cleanURL = replace(messyURL, "//", "/", "all");
// Fix the protocol part that got broken
cleanURL = replace(cleanURL, "https:/", "https://");
writeOutput("<h3>Fix Double Slashes in URLs</h3>");
writeOutput("<p><strong>Messy URL:</strong> " & messyURL & "</p>");
writeOutput("<p><strong>Clean URL:</strong> " & cleanURL & "</p><br>");
// Example 2: Convert file paths
windowsPath = "C:\Users\John\Documents\file.txt";
webPath = replace(windowsPath, "\", "/", "all");
writeOutput("<h3>Convert Windows Paths</h3>");
writeOutput("<p><strong>Windows Path:</strong> " & windowsPath & "</p>");
writeOutput("<p><strong>Web Path:</strong> " & webPath & "</p><br>");
// Example 3: Clean up user input
userInput = "Hello!!! How are you??? ";
cleaned = replace(userInput, "!!!", "!", "all");
cleaned = replace(cleaned, "???", "?", "all");
cleaned = trim(cleaned);
writeOutput("<h3>Clean User Input</h3>");
writeOutput("<p><strong>Original:</strong> '" & userInput & "'</p>");
writeOutput("<p><strong>Cleaned:</strong> '" & cleaned & "'</p><br>");
// Example 4: Format text for display
rawText = "price:$25.99|qty:2|total:$51.98";
formatted = replace(rawText, "|", " • ", "all");
formatted = replace(formatted, ":", ": ", "all");
writeOutput("<h3>Format Text for Display</h3>");
writeOutput("<p><strong>Raw Data:</strong> " & rawText & "</p>");
writeOutput("<p><strong>Formatted:</strong> " & formatted & "</p>");
</cfscript>
Simple word replacement
Replace words to change meaning or fix typos.
<cfscript>
writeOutput("<hr><h2>4. Simple Word Replacement</h2>");
// Example 1: Fix common typos
textWithTypos = "The recieve was good, but I definately prefer the original.";
fixed = replace(textWithTypos, "recieve", "receive");
fixed = replace(fixed, "definately", "definitely");
writeOutput("<h3>Fix Typos</h3>");
writeOutput("<p><strong>With typos:</strong> " & textWithTypos & "</p>");
writeOutput("<p><strong>Fixed:</strong> " & fixed & "</p><br>");
// Example 2: Change gender pronouns
story = "He went to his car and drove to his house.";
changed = replace(story, "He", "She", "all");
changed = replace(changed, "his", "her", "all");
writeOutput("<h3>Change Pronouns</h3>");
writeOutput("<p><strong>Original:</strong> " & story & "</p>");
writeOutput("<p><strong>Changed:</strong> " & changed & "</p><br>");
// Example 3: Replace technical terms with simple words
technical = "The algorithm will optimize the performance of your system.";
simple = replace(technical, "algorithm", "program");
simple = replace(simple, "optimize", "improve");
writeOutput("<h3>Simplify Technical Terms</h3>");
writeOutput("<p><strong>Technical:</strong> " & technical & "</p>");
writeOutput("<p><strong>Simple:</strong> " & simple & "</p><br>");
// Example 4: Change brand names
text = "I use Google for search and Google Drive for storage.";
generic = replace(text, "Google", "a search engine", "one");
generic = replace(generic, "Google Drive", "cloud storage");
writeOutput("<h3>Make Text Generic</h3>");
writeOutput("<p><strong>Branded:</strong> " & text & "</p>");
writeOutput("<p><strong>Generic:</strong> " & generic & "</p>");
writeOutput("<p><em>Notice 'one' parameter replaced only first 'Google'</em></p>");
</cfscript>
