Skip to main content
Known Participant
May 27, 2009
Question

When and how to trim string

  • May 27, 2009
  • 1 reply
  • 1030 views

Not sure the best way around this issue.  In a query I have the following:

SUBSTRING(blogStories.blogBody,1,220) AS blogBody

Later, when I go to display this, I want to strip the html so I have this:

<cfset trimmedBodyText = REReplaceNoCase(#rsBlog.blogBody#,"<[^>]*>","","ALL")>

<p><cfoutput>#trimmedBodyText#</cfoutput><em> ... (more)</em></p>

This is where the problem comes in.  If my SQL query happens to end in the middle of a string like this:

<p>Web 2.0 tools allow opportunities for doing traditional things in new and fundamentally different ways. As Clay Shirky writes in <a target="_blank" href="http://perma://BLPageReference/75484FCE-115D-450B-A2DF-4F71745B

Then the REReplaceNoCase causes problems because there is no end tag.

Can I do this in SQL, or should I pull the whole story, do the REReplaceNoCase and then trim it?  If so, what is the command in ColdFusion for trimming?  Everything I've found only trims spaces. I can't seem to specify a length anywhere.

This topic has been closed for replies.

1 reply

Known Participant
May 28, 2009

OK, I hadn't received an answer and I kept digging and found the LEFT command, so what I have done is changed my query to get the entire story then I run this code for the output

<cfset variables.blogStory = REReplaceNoCase(#rsBlog.blogStory#,"<[^>]*>","","ALL")>

<cfset variables.blogStory = Left(#variables.blogStory#, 220)>

<p>#variables.blogStory#<em>... (more)</em></p></td>

Then the problem was that sometimes I'd get cut off in the middle of a word, so I've changed it to this to find the last word and remove it:

<cfset variables.blogStory = REReplaceNoCase(#rsBlog.blogStory#,"<[^>]*>","","ALL")>
<cfset variables.blogStory = Left(#variables.blogStory#, 220)>
<cfset variables.lastWord = ListLast(#variables.blogStory#, " ")>
<cfset variables.trimLength = Len(#variables.lastWord#)>
<cfset variables.blogStory = Left(#variables.blogStory#, 220-#variables.trimLength#)>
<p>#variables.blogStory#<em>... (more)</em></p></td>

This solves the problem for me.  I get the output I want, but I'm sure there is a more elegant way of doing this with less code.  If anyone knows of one, I'd love to hear it.

BKBK
Community Expert
Community Expert
May 30, 2009

<cfset variables.blogStory = REReplaceNoCase(rsBlog.blogStory,"<[^>]*>","","ALL")>
<cfset variables.blogStory = left(variables.blogStory, 220)>
<cfset variables.length = listLen(variables.blogStory, " ")>
<cfset variables.blogStory = listDeleteAt(variables.blogStory, variables.length, " ")>

Known Participant
May 30, 2009

Thanks, that does take a line of code out and is a better way to do it for sure.

I was really hoping this could be done in the SQL query, but I guess that's not possible