Each operating system uses special characters to indicate the start of the new line. For example, Unix-based systems (Linux, macOS X, Android, etc.) uses the \n character, also known as Line Feed (LF) character, to move the cursor to the next line.

Windows uses \r\n characters to specify the start of the line, sometimes also called Carriage Return and Line Feed (CRLF).

In this short article, we'll look at replacing all new line characters in a string with an HTML line-break (<br>) tag so that it can be displayed as a multi-line string.

Let us say we have got the following address:

2683 Jerry Toth Drive
New York NY 10010
United States

Now we want to display this address on multiple lines in an HTML web page. Here is how you can do it:

String address = "ACME Inc.\n" +
        "2683 Jerry Toth Drive\n" +
        "New York NY 10010\n" +
        "United States";

// Replace new line with <br>
String html = address.replaceAll("(\r\n|\n)", "<br>");

// Print HTML string

Here is the output:

ACME Inc.<br>2683 Jerry Toth Drive<br>New York NY 10010<br>United States

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.