Convert Text Line Breaks to HTML in Classic ASP

Use Replace() to turn the line breaks in a Classic ASP / VBScript string into visible HTML breaks. When text comes from a visitor or another untrusted source, HTML-encode the text first, then replace the newline characters.

Quick working example

<%
Dim textValue, safeText
textValue = "First line" & vbCrLf & "Second line"
safeText = Server.HTMLEncode(textValue)
Response.Write Replace(safeText, vbCrLf, "<br>")
%>

Output:

First line
Second line
Why encode first? Server.HTMLEncode() treats the original text as text, not executable HTML. The replacement then introduces only the intended <br> tags.

Why line breaks disappear in HTML

Line breaks created by pressing Enter in a textarea form field are real characters in the submitted text. However, normal HTML rendering collapses most whitespace into a single space. Therefore a string that has several lines in VBScript can appear as one line in a web page.

Use <br> when each original text newline should become a visible break. Do not add a series of <br> elements simply to create spacing in the page layout; use CSS spacing for that.

Back to top ↑

VBScript newline constants

Different sources can use different end-of-line characters. The following VBScript constants help you identify and work with them:

ConstantCharacter(s)Typical use
vbCrLfChr(13) & Chr(10)Windows-style carriage return followed by line feed
vbLfChr(10)Unix/Linux-style line feed
vbCrChr(13)Older Mac-style carriage return
vbNewLinePlatform-dependent line endingConvenient in generated VBScript strings; on IIS/Windows, CRLF is typical

If the string was built on your Windows server, vbCrLf is often sufficient. For text from external systems or files, handle all three variants.

Reference: Microsoft documentation for VB newline constants.

Back to top ↑

Replace vbCrLf with an HTML break

The basic syntax is Replace(expression, find, replace). This replaces all occurrences of the specified line-ending sequence:

Replace(text_variable, vbCrLf, "<br>")

The original example works when the input is known to be safe HTML or contains only trusted text. For untrusted text, use the encoded version shown in the next section.

In VBScript, a single quote begins a comment. Write "<br>" using double quotes; '<BR>' is not a string literal.

You can create newline characters directly in VBScript by concatenating vbCrLf:

Dim message
message = "Name: Ava" & vbCrLf & "City: Hyderabad"
Response.Write Replace(Server.HTMLEncode(message), vbCrLf, "<br>")

Output: Name: Ava, followed by City: Hyderabad on the next line.

Back to top ↑

Encode visitor-controlled text before inserting HTML

When the text is submitted through Request.Form(), retrieved from a database, or read from a file, treat it as untrusted unless there is a strong reason otherwise. Always apply Server.HTMLEncode() before converting newlines to HTML breaks.

<%
Dim userMessage, encodedMessage
userMessage = Request.Form("message")
encodedMessage = Server.HTMLEncode(userMessage)
Response.Write Replace(encodedMessage, vbCrLf, "<br>")
%>

For example, a visitor might submit the literal characters <b>Hello</b>. With HTML encoding, those characters remain visible as text rather than creating a bold element in the resulting document.

Do not reverse the order: if you replace the newline with <br> and then HTML-encode the result, the browser will display <br> as text instead of a line break.

This output-encoding guidance also applies when handling feedback messages and other submitted form values.

Back to top ↑

Handle Windows CRLF, Unix LF, and older Mac CR

A simple replacement of vbCrLf does not handle every possible newline character. The next example converts all three forms to a single vbLf, then replaces that normalized character with <br>.

<%
Dim inputText, safeText
inputText = "First" & vbCrLf & "Second" & vbLf & "Third" & vbCr & "Fourth"
safeText = Server.HTMLEncode(inputText)
safeText = Replace(safeText, vbCrLf, vbLf)
safeText = Replace(safeText, vbCr, vbLf)
safeText = Replace(safeText, vbLf, "<br>")
Response.Write safeText
%>

Output:

First
Second
Third
Fourth

Order matters: normalize the two-character vbCrLf sequence first. Otherwise replacing vbCr and vbLf separately can turn one CRLF into two HTML breaks.

If you need to reuse this processing, wrap it in a function:

<%
Function TextToHtmlLines(value)
    If IsNull(value) Then
        TextToHtmlLines = ""
        Exit Function
    End If

    Dim result
    result = Server.HTMLEncode(CStr(value))
    result = Replace(result, vbCrLf, vbLf)
    result = Replace(result, vbCr, vbLf)
    TextToHtmlLines = Replace(result, vbLf, "<br>")
End Function

Response.Write TextToHtmlLines("Line one" & vbCrLf & "Line two")
%>

This function also handles Null values rather than passing them into Replace(), which would otherwise raise an error.

Back to top ↑

Complete Classic ASP textarea form example

Save the following as linebreak-demo.asp on an IIS server with Classic ASP enabled. Submit a message containing two or more lines to see the displayed output. The code safely encodes the displayed message and retains line breaks.

<%@ Language="VBScript" %>
<%
Dim message, encodedMessage
message = ""
If Request.ServerVariables("REQUEST_METHOD") = "POST" Then
    message = Request.Form("message")
End If
encodedMessage = Server.HTMLEncode(message)
%>
<!doctype html>
<html><head><title>Textarea line breaks</title></head><body>
<form method="post" action="linebreak-demo.asp">
    <label for="message">Your message</label><br>
    <textarea id="message" name="message" rows="5" cols="40"><%= encodedMessage %></textarea><br>
    <button type="submit">Show message</button>
</form>
<%
If Request.ServerVariables("REQUEST_METHOD") = "POST" Then
    encodedMessage = Replace(encodedMessage, vbCrLf, vbLf)
    encodedMessage = Replace(encodedMessage, vbCr, vbLf)
    encodedMessage = Replace(encodedMessage, vbLf, "<br>")
    Response.Write "<h2>Submitted text</h2><p>" & encodedMessage & "</p>"
End If
%>
</body></html>

The name="message" attribute is what makes the textarea accessible through Request.Form("message"). The form posts to the same example file; change the action value only if you use a different filename.

For a separate form-processing tutorial, see Classic ASP forms and the Request object. To see a previously published example, open the Plus2Net textarea line-break demo.

Back to top ↑

CSS alternative: preserve line breaks without Replace()

You do not always need to insert HTML breaks. CSS can preserve line endings while leaving the content HTML-encoded. Use white-space: pre-line when you want the line breaks but not repeated spaces; use white-space: pre-wrap when indentation and repeated spaces should be visible too.

<%
Dim message
message = "First line" & vbCrLf & "    Indented second line"
Response.Write "<div style=""white-space:pre-wrap;overflow-wrap:anywhere;"">" & _
    Server.HTMLEncode(message) & "</div>"
%>

Here, Server.HTMLEncode() protects the original text, and the browser uses CSS to show the newlines. This is particularly convenient for displaying notes, comments, addresses, or formatted text stored in a database.

ApproachBest suited for
Replace(..., vbCrLf, "<br>")Generating HTML with explicit line break elements
white-space: pre-lineRetaining newlines while collapsing ordinary extra spaces
white-space: pre-wrapPreserving both newlines and repeated spaces

More details are available in the HTML line-break tutorial and the PHP line-break handling tutorial.

Back to top ↑

Display multiline text read from a server file

The same technique works when FileSystemObject reads a text file. Use a fixed path controlled by the application, check that the file exists, and HTML-encode the contents before displaying them.

<%
Const ForReading = 1
Dim fso, filePath, textFile, contents
filePath = Server.MapPath("notes.txt")
Set fso = Server.CreateObject("Scripting.FileSystemObject")

If fso.FileExists(filePath) Then
    Set textFile = fso.OpenTextFile(filePath, ForReading)
    contents = textFile.ReadAll
    textFile.Close
    Set textFile = Nothing

    contents = Server.HTMLEncode(contents)
    contents = Replace(contents, vbCrLf, vbLf)
    contents = Replace(contents, vbCr, vbLf)
    Response.Write Replace(contents, vbLf, "<br>")
Else
    Response.Write "Text file not found."
End If
Set fso = Nothing
%>

In this example, notes.txt must exist alongside the .asp script. Do not build a file path directly from a visitor-submitted value.

Back to top ↑

More line-break examples

Join an array into multiple lines

Use Join() to combine array elements with a newline separator, then display the result:

Dim lines, message
lines = Array("Monday", "Tuesday", "Wednesday")
message = Join(lines, vbCrLf)
Response.Write Replace(Server.HTMLEncode(message), vbCrLf, "<br>")

Count lines in a string

For text that may use mixed newline formats, normalize the newlines and count the parts after Split():

Dim message, normalized, lines
message = "Apple" & vbCrLf & "Banana" & vbLf & "Cherry"
normalized = Replace(message, vbCrLf, vbLf)
normalized = Replace(normalized, vbCr, vbLf)
lines = Split(normalized, vbLf)
Response.Write "Line count: " & (UBound(lines) - LBound(lines) + 1)

Output: Line count: 3. An empty input string requires separate handling if you define its line count as zero rather than one.

Preserve intentional blank lines

Two consecutive line-ending sequences represent a blank line. The normalized Replace() technique retains both breaks; CSS pre-wrap can preserve them too.

Dim note
note = "Paragraph one" & vbCrLf & vbCrLf & "Paragraph two"
Response.Write Replace(Server.HTMLEncode(note), vbCrLf, "<br>")

Use paragraph tags for structured page content where paragraphs—not raw text lines—are intended. Line-break conversion is most appropriate when you must preserve the original user-entered formatting.

Back to top ↑

Common problems and troubleshooting

ProblemLikely causeSolution
Text still displays on one lineThe source has vbLf rather than vbCrLfNormalize all newline variants before converting them.
The page prints <br> literallyOutput encoding was applied after inserting HTML breaksEncode original text first, then replace the line endings.
Extra blank lines appearCR and LF were replaced separately, doubling CRLF line breaksConvert vbCrLf first.
Single-quote syntax causes strange outputVBScript treats ' as a comment delimiterUse "<br>" for string literals.
Invalid use of Null errorA missing/nullable value reached Replace()Check IsNull() and handle the value before replacing.
User-supplied HTML renders unexpectedlyThe original text was not HTML-encodedUse Server.HTMLEncode() before adding break tags.
Whitespace indentation is lostNormal HTML rendering collapses repeated spacesUse white-space: pre-wrap when spacing is important.

If you are new to the output statement, see Response.Write(). For general text transformations, refer to Replace() and the VBScript string function reference.

Back to top ↑

Frequently asked questions

Does vbCrLf automatically create an HTML line break?

No. It adds a carriage return and line feed to the underlying string. In normal HTML, these characters do not create a visible line break unless CSS preserves the whitespace or you output an HTML <br> element.

Why is vbCrLf not always enough?

Text can come from other operating systems, web services, or files that use only LF or CR characters. Normalizing all three common forms ensures they display consistently.

Should I run Server.HTMLEncode() before or after Replace()?

For user-controlled text, encode the text before inserting <br> elements. Otherwise either the original HTML may be interpreted by the browser or the intended break tags will be escaped.

Is white-space: pre-wrap better than Replace()?

It depends on the output you need. pre-wrap preserves newlines and repeated spaces without inserting HTML tags. Replace() is appropriate when you specifically need HTML break elements.

Can I use this method with a textarea submitted through POST?

Yes. Read Request.Form("message"), encode the value, normalize its newline characters, and then display it using Replace() or CSS. See the complete example above.

Will multiple blank lines stay visible?

Yes. Each newline can become its own <br>; two consecutive newlines create two breaks. However, browser layout may still depend on surrounding markup and CSS.

Is there a direct nl2br() function in VBScript?

Classic ASP with VBScript does not provide PHP's nl2br() as a built-in function. Use Replace(), a helper function, or CSS whitespace handling instead.

Back to top ↑

Back to top ↑


ASP Home






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer