Kalanamith
Kalanamith

Reputation: 20648

How to encode strings in ColdFusion excluding the "dot"

I am looking for a way to encode strings with ColdFusion but excluding the ".". This is what I have tried so far:

<!--- Test area --->
<cfset str="ChrisTilghmanFirstFlash.Eflv">
<cfset str1="Chris Tilghman First Flash.Eflv">
<cfset str2="Chris-Tilghman First_Flash.Eflv">
<cfset enc1 = urlEncodedFormat(str,"utf-8" )>
<cfset enc2 = urlEncodedFormat(str1,"utf-8")>
<cfset enc3 = urlEncodedFormat(str2,"utf-8")>
<cfoutput>#enc1#</cfoutput><br>
<cfoutput>#enc2#</cfoutput><br>
<cfoutput>#enc3#</cfoutput><br>
<!--- END test area --->

The urlEncode utf-8 other encodes the "dot", "-" and "_" characters too. How do I prevent this scenario?

Upvotes: 3

Views: 4409

Answers (4)

Leigh
Leigh

Reputation: 28873

(Too long for comments ...)

I came across this thread while trying to implement RFC 3986 encoding. In case you are using the newer encodeForURL function (instead of urlEncodedFormat) it gets you a little closer, but still requires a few tweaks.

According to RFC 3986:

  • Unreserved characters that should not be escaped: ALPHA / DIGIT / "-" / "." / "_" / "~" /
  • Spaces should be encoded as %20 instead of +
  • Reserved characters that should be escaped include: : / ? ## [ ] @ ! $ & ' ( ) * + , ; =

To make the results of EncodeForURL compatible:

  • Force encoding of asterisk "*" (reserved character)
  • Reverse the encoding of tilde "~" (should not be encoded).
  • Change space encoding from "+" to "%20":

Code:

encodedText = encodeForURL("space period.asterisk*");
encodedText = replaceList( encodedText , "%7E,+,*", "~,%20,%2A");

Upvotes: 0

Kalanamith
Kalanamith

Reputation: 20648

One answer can be found in this thread, which

Use[s] ColdFusion's ReplaceList() function to "correct" the errors made by URLEncodedFormat() to produce an RFC 3986 compliant URL encoded string.

Code:

<cfset string = replacelist(urlencodedformat(string), "%2D,%2E,%5F,%7E", "-,.,_,~")>

Upvotes: 2

ale
ale

Reputation: 6430

You could use the dot as a list separator and encode each item in the list separately. Something like this:

<cfset enc1="">
<cfloop list="#str#" index="i" delimiter=".">
  <cfset listAppend(enc1,urlEncodedFormat(i,"utf-8"),".")>
</cfloop>

Upvotes: 3

baynezy
baynezy

Reputation: 7056

This will solve it for you:-

<cfset str="ChrisTilghmanFirstFlash.Eflv">
<cfset str1="Chris Tilghman First Flash.Eflv">
<cfset str2="Chris-Tilghman First_Flash.Eflv">
<cfset enc1 = urlEncodedFormat(str,"utf-8" )>
<cfset enc2 = urlEncodedFormat(str1,"utf-8")>
<cfset enc3 = urlEncodedFormat(str2,"utf-8")>
<cfoutput>#replace(enc1, "%2E", ".", "ALL")#</cfoutput><br>
<cfoutput>#replace(enc2, "%2E", ".", "ALL")#</cfoutput><br>
<cfoutput>#replace(enc3, "%2E", ".", "ALL")#</cfoutput><br>

Upvotes: 3

Related Questions