Yesterday, I found myself needing more than ColdFusion could supply. I had a variable with content that came from a WYSIWYG editor. Some of that content was the result of inserting images into the content. By default the image source was set to the absolute path from the webroot (i.e. /images/imagefile.jpg). This worked great for the web, but I needed the same content to be sent via email which did not work so well.
I needed to find all instances of the “src” attribute and tack on a domain so the ending result would be http://domain.com/images/imagefile.jpg and therefore would be email friendly. I tried several ways of doing this (combinations of REFind, REMatch, etc) but everything ended up being more difficult than it should have been.
Luckily, a ColdFusion String maps directly to a Java String so even though the docs might not suggest it, there are methods available for use. The one I wanted was “replaceAll()”. It does a simple regex replace and allows for backreferencing ($1, $2, etc). Backreferencing is key to not lose content that I needed (i.e. /images/imagefile.jpg). So, here’s the code that finally made my day:
<cfset domainName = "http://domain.com" />
<cfset contentVariable = contentVariable.replaceAll("src=\""(\/.+?)\""", "src=\""#domainName#$1\""") />
Full documentation on Java’s String functions can be seen at the Java Docs -> String