views:

221

answers:

1

I would like to insert a line break into the first space between words in a string variable. Here is my code so far:

    <cfset myPosition = find(" ", #myVar#)>
    <cfset lineBreak = Chr(13)&Chr(10)>
    <cfset myVar = insert(#lineBreak#, #myVar#, #myPosition#)>

What am I doing wrong?

+5  A: 

I don't think that you are doing anything wrong. Your code seems to work. When you output your variable, try wrapping it in <pre></pre> tags for testing purposes. If you want the linebreak to show up on a html page you have to replace the space with <br />.

This works for me and shows the carriagereturn / linefeed:

<cfset myVar="The quick brown fox">
<cfset myPosition = find(" ", myVar)>
<cfset lineBreak = Chr(13) & Chr(10)>
<cfset myVar = insert(lineBreak, myVar, myPosition)>
<cfoutput>
   <pre>#myVar#</pre>
</cfoutput>

BTW: there is no need to enclose your variables in #'s unless you want to output the variable or to have it evaluated between quotation marks.

Andreas Schuldhaus
I do want the linebreak to show up on an html page. Is there any reason I shouldn't use <pre> to show the line break?
dmr
I wouldn't recommend using the <pre> unless you know what you are doing. It defines a block of preformatted text. It renders text with a fixed-pitch font and may disable automatic word wrap. It leaves white space intact and that is the reason why the linefeed shows up. If you don't need a fixed-width font HTML Markup is the way to go.
Andreas Schuldhaus