How to I get a text field from a database to word wrap to a specific width, while maintaining paragraph spacing?

101 views Asked by At

I have researched this for days now and everything I have tried has failed. I am using classic ASP and MySql database.

I am not sure where else to turn. I have read similar questions here, but the solutions did not work for me.

Any help will be most appreciated.

I tried using <p STYLE="word-wrap: break-word;width:200"><%=V12%></p> and this gave me the correct wrapping, but didn't keep the paragraph spacing.

I tried using <pre> and this gave me the spacing, but gave me no word wrap.

I tried V12 = Replace(INFO1("STORY_"),vbCrLf,"<BR>") and this did nothing.

2

There are 2 answers

0
John On

To preserve line breaks from a database field I used to use

replace(rs("myfieldname"),chr(13),"<br>")

However for the last few years I've been using the CSS style white-space: pre-line. It's client side code (obviously) so you can use it with whatever back end you have.

0
Adam On

You're replacing VBCrLf when you need to be replacing VBLf (or ideally both).

Depending on the OS/software used to create a string, a line break can either be represented as a line feed (VBLf or Chr(10)) or a carriage return and a line feed (VBCrLf or Chr(13)). You can have a carriage return on it's own, but this wouldn't initiate a new line I don't think.

This answer/thread explains it well:

https://stackoverflow.com/a/12747850/4901783

So when replacing line breaks, you need to check for both VBLf and VBCrLf.

As for paragraph formatting, replacing a line break with </p><p> will close an existing paragraph and open a new one. Just as long as you also wrap the output in p markers too.

You could do all of this in a function, such as:

Function lb_to_p(ByVal Str)

    Str = Trim(Str)

     ' Replace all line breaks with </p><p> to indicate that the paragraph 
     ' has ended and a new one should start.

    Str = Replace(Str,VBCrLf,"</p><p>")
    Str = Replace(Str,VBCr,"</p><p>")
    Str = Replace(Str,VBLf,"</p><p>")

    ' Wrap the string in paragraph markers.

    Str = "<p>" & Str & "</p>"

    ' Remove any instances of <p></p>. This could happen if there's consecutive  
    ' line breaks, or the string starts or ends with a line break. 

    Str = Replace(Str,"<p></p>","")

    lb_to_p= Str

End Function