Replace new line (\n) with HTML br tag in string using Java

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:

ACME Inc.
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
System.out.println(html);

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.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.