Whatever message this page gives is out now! Go check it out!
Replace(string, searchstring, replacestring|obj [, scope ][,start])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 |
|
start | Position to start searching in the string (defaults to 1). |
replace("The quick brown fox jumped over the lazy cow, dog, and cat.",",","","All") |
<cfoutput>#replace("The quick brown fox","o","cf","all")#</cfoutput><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><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><cfoutput>
#replace("The quick brown fox","fox","dog")#
</cfoutput><cfoutput>
#replace("The quick brown fox jumped over the brown dog","brown","black")#
</cfoutput><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><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><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><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>