Whatever message this page gives is out now! Go check it out!

Replace

Last update:
May 18, 2026

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

Parameter
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
  • one: replaces the first occurrence (default)
  • all: replaces all occurrences
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.
Note:
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, "<", "&lt;", "all");
                sanitizedData = replace(sanitizedData, ">", "&gt;", "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>

Share this page

Was this page helpful?
We're glad. Tell us how this page helped.
We're sorry. Can you tell us what didn't work for you?
Thank you for your feedback. Your response will help improve this page.

On this page