Friday, March 12, 2010

Break a String at a Specific Character Width

This snippet will break a string into lines that contain no more than the specified character count. It will not chop off a line mid word, instead it will place the line break at the last space before the line break character limit.

This snippet can be useful for sending plain text email where the character count of each line must not exceed a certain length.

<cfset string = "">
<cfset size = "80">
<cfset lineBreak = chr(13) & chr(10)>

<cfset outputString = "">
<cfloop list="#string#" index="word" delimiters=" ,#chr(13)##chr(10)#,#chr(13)#">
<cfif len(trim(listLast(outputString,lineBreak)) & " " & word) gt size>
<cfset outputString = outputString & lineBreak>
</cfif>
<cfset outputString = outputString & word & " ">
</cfloop>
<cfset outputString = replace(outputString," " & lineBreak,lineBreak,"ALL")>

<cfoutput><pre>#trim(outputString)#</pre></cfoutput>

No comments:

Post a Comment