user460114
user460114

Reputation: 1848

ColdFusion - Remove spaces from text that exists between tags

I have the following string

Brad Thorm signs for the <hash>All Blacks</hash>

It may not be "All Blacks" between the tags, It could be anything. I need to parse this string such that when the <hash></hash> tags are encountered:

  1. Remove all spaces from the string between the tags, i.e. "All Blacks" should become "AllBlacks"
  2. Add a "#" symbol to the front of the string between the tags, i.e. "AllBlacks" becomes "#AllBlacks"

Looking for the cleanest way to do this.

Upvotes: 1

Views: 2021

Answers (2)

Matt Gifford
Matt Gifford

Reputation: 1268

Reworking Chris' code into a function and looping the array, this works for multiple hash instances within the provided string:

<cffunction name="renderHash" output="false" returnType="string">
    <cfargument name="text" required="true" type="string" hint="The text to render." />
        <cfset var strText      = arguments.text />
        <cfset var strHash      = '' />
        <cfset var arrMatches   = reMatch("<hash>(.*?)</hash>", arguments.text) />
            <cfloop array="#arrMatches#" index="i">
                <cfset strHash = reReplace(i, "<hash>(.*?)</hash>", "\1") />
                <cfset strHash = reReplace(strHash, "[[:space:]]", "", "ALL") />    
                <cfset strHash = "##" & strHash />
                <cfset strText = replace(strText, i, strHash) />
            </cfloop>
    <cfreturn strText />
</cffunction>

Pass the string to convert into the function and you're done:

<cfset strText = '<hash>Brad Thorm</hash> signs for the <hash>All Blacks</hash>' />
<cfset strConverted = renderHash(strText) />

Upvotes: 3

Chris Blackwell
Chris Blackwell

Reputation: 2178

There might be cleaner ways to do this, but this will turn any text between tags into a #hashtag, and handle multiple tags in a string

<cfscript>
text = "<hash>Brad Thorm</hash> signs for the <hash>All Blacks</hash>";
matches = rematch("<hash>(.*?)</hash>", text);
for(match in matches) {
    hashtag = reReplace(match, "<hash>(.*?)</hash>", "\1");
    hashtag = reReplace(hashtag, "\W", "", "all");
    hashtag = "##" & hashtag;
    text = replace(text, match, hashtag);
}

writeoutput(text);
</cfscript>

Upvotes: 2

Related Questions