DEV Community

James Moberg
James Moberg

Posted on

TokenReplace - A ColdFusion User-Defined Function

I've worked with different projects that perform tokenization differently; often it involves using different delimiters. While researching I saw that Drupal (which I don't use) has an official TokenReplace function documented in their API. I thought I'd write something similar since this this doesn't appear to be a function that Adobe ColdFusion currently has.

Usage

Create a string with tokens.

Here are some samples. (I don't personally recommend using HTML brackets, pound signs or parenthesis, but some frameworks use them.)

Hello {name}?  Is this {address}?  I have a special delivery for '{ccName}'.
Hello [name]?  Is this [address]?  I have a special delivery for '[ccName]'.
Hello <name>?  Is this <address>?  I have a special delivery for '<ccName>'.
Hello :name:?  Is this :address:?  I have a special delivery for ':ccName:'.
Hello <<name>>?  Is this <<address>>?  I have a special delivery for '<<ccName>>'.
Hello ::name::?  Is this ::address::?  I have a special delivery for '::ccName::'.
Hello #name#?  Is this #address#?  I have a special delivery for '#ccName#'.
Hello %name%?  Is this %address%?  I have a special delivery for '%ccName%'.
Hello -name-?  Is this -address-?  I have a special delivery for '-ccName-'.
Enter fullscreen mode Exit fullscreen mode

Create a data structure.

(NOTE: The token is not case-sensitive.)

replacementData = {
  "name" = "Bruce Wayne",
  "Address" = "1007 Mountain Drive, Gotham",
  "ccName" = "The Dark Night"
}
Enter fullscreen mode Exit fullscreen mode

Use the UDF

TokenReplace(Text, replacementData, "{", "}")
// Hello Bruce Wayne?  Is this 1007 Mountain Drive, Gotham?  I have a special delivery for 'The Dark Night'.
Enter fullscreen mode Exit fullscreen mode

NOTE: ReEscape may be an Adobe ColdFusion-only function, but BlueDragon supports it too. I'm not sure what the equivalent Lucee function is. (UPDATE: I replaced the ACF built-in function with the REEscape UDF from CFLib.)

TryCF Demo

https://trycf.com/gist/18e4d1662e8417fc824e264b2490dd1b

Source

https://gist.github.com/JamoCA/18e4d1662e8417fc824e264b2490dd1b

Top comments (0)