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

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Jul 24, 2021. Topics: Java.
Canonical URL: https://attacomsian.com/blog/java-replace-newline-character-with-html-line-break

> A quick guide to learn how to replace all new line characters in a string with an HTML line break (br) tag 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:

```plaintext
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:

```java
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:

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