Avg. Rating 1.0

Problem

A string is preceded and followed by a number of same characters but trim() only trim off spaces

Solution

Use regular expression to trim off the unwanted characters

Detailed explanation

Suppose during processing, you have a string ended up with being like this:

-----------here is my text-----

Or you have a list and for whatever reason, you remove the items but have the commas left over like this:

,,,,,,,,,,,,,item1,item2,item3,,,,

And you want to trim off those dashes or commas. Trim() does not work here as it only trims off spaces, but luckily regular expressions come for a rescue. We can use regexp to remove all the starting and trailing dashes:

<cfset str = reReplace(result, "^(\-)+|(\-)+$", "", "ALL")>

And here is a UDF for reusability:

<cffunction name="trimChar" access="public" returntype="string" hint="" output="false">
    <cfargument name="str" type="string" required="yes" hint="The text to be trimmed">
    <cfargument name="char" type="string" required="yes" hint="The char(s) to be trimmed">
    <cfset var result = "">
    <cfset var c = "">
    <cfset var i = "">
    <cfset var size = len(arguments.char)>
    
    <cfset result = arguments.str>
    
    <!--- Trim off every character, one by one --->
    <cfloop from="1" to="#size#" index="i">
        <cfset c = mid(arguments.char, i, 1)>
       
        <cfset result = reReplace(result, "^(\#c#)+|(\#c#)+$", "", "ALL")>
    </cfloop>
    
    <cfreturn result>

</cffunction>

I added in one more feature in this UDF that allows user to pass in multiple characters. For example, for this string:

((((((((here is my text)))))

They can pass in both parentheses to trim both of them off:

<cfset str = trimChar(str, "()")>

 

 

 


+
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.

Report abuse

Related recipes