Replace

Description

Replaces occurrences of substring1 in a string with an object in a specified scope. The search is case sensitive.

This function can take either string or callback function as an argument instead of the argument to replace the string.

Returns

The string, after making replacements.

Category

String functions

Function syntax

Replace(string, substring, obj [, scope ],start)

History

ColdFusion (2021 release):

  • Added the parameter start.
  • Also, callback support is added.

Parameters

Parameter

Description

string

A string or a variable that contains one. String in which to search.

substring1

A string or a variable that contains one. String for which to search

obj

String that replaces substring1 or callback function. You can also pass a callback function in this argument.

function(transform,position,original) {...}

scope

  • one: replaces the first occurrence (default)
  • all: replaces all occurrences

start

Position to start searching in the string (starts at 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 with callback function

<cfscript>
       myStr="happy app application apply appreciate appreciation Apprentice";
       
       outStr = replace( myStr, "app", function (transform, position, original){
                    return UCase(transform);
             }, "all");
       writeoutput(outStr);
</cfscript>

The code produces the following output:

hAPPy APP APPlication APPly APPreciate APPreciation APPrentice

Example 2

<cfscript> 
  mystring="The quick brown fox jumped over the lazy cow." 
  substring="ow" 
  replacement="aze" 
  scope="ALL" 
  start=len("The quick brown") 
  writeOutput(replace(mystring,substring,replacement,scope,start)) 
  writeOutput("<br/>") 
  // Scope="ONE" 
  writeOutput(replace(mystring,substring,replacement,"ONE",start)) 
</cfscript> 

Output

The quick brown fox jumped over the lazy caze.
The quick brown fox jumped over the lazy caze.

Example 3

<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.

 Adobe

Get help faster and easier

New user?