New Line Literal in JavaScript Alert Box

Mohammed Imtiyaz Mar 4, 2015

This tutorial will explain you how to use newline character literal in ASP.Net using C# and VB.Net

Suppose you have a string in your page load event as follows:

C#

protected void Page_Load(object sender, EventArgs e)
{
    string strText = "First line Second line Third line Fourth line";
    Response.Write(strText);
}

VB

Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load			
    Dim strText As String = "First line Second line Third line Fourth line"
    Response.Write(strText)
End Sub

When you run this code, the output will be as follows:

Output: First line Second line Third line Fourth line

Assume that you want to break this string at some specific length. You can do it by simply modifying the above code as follows:

Add New Line Literal "\n" and Carriage Return Literal "\r" at the point where you want to break the string and replace those literals with breakline "<br />"

C#

protected void Page_Load(object sender, EventArgs e)
{
    string strText = "First line\r\n Second line\r\n Third line\r\n Fourth line";
    strText = strText.Replace("\r\n", "<br />").Replace("\r", "<br />");
    Response.Write(strText);
}

VB

Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
	Dim strText As String = "First line\n\r Second line\n\r Third line\n\r Fourth line"
	strText = strText.Replace("\n\r", "<br />").Replace("\r", "<br />")
	Response.Write(strText)
End Sub
Output:
First line
Second line
Third line
Fourth line