This blog post will talk about how to replace new line with HTML br tag in string using Java.
If you are working on a project that requires the ability to replace new lines with HTML br tags, then this article is for you! We’ll start by taking a look at some code examples and discussing their functionality.
All operating systems have some special characters to determine a line break. Unix-based systems like Ubuntu and Android uses the \n character to move the cursor to the next line. Windows uses \r\n. And HTML language uses br tag to indicate a new line.
If you are working on a Java web app and needs to replace line break in a string with br tag, here are some examples for you.
import java.util.*; import java.lang.*; import java.io.*; class JavaExample { public static void main (String[] args) throws java.lang.Exception { String source = "Java is a programming language that can be used \n" + "to create web applications, Android apps, and much more.\n" + " it's easy to learn and it provides many features such as data types, operators, expressions, \n" + "statements, control structures and other elements that make up computer programs."; String output = source.replaceAll("(\r\n|\n)", "<br>"); System.out.println(output); } }
As you see in the example, we use replaceAll() method of String class to replace \r\n or \n (\r\n|\n)
with br tag. The out put wil be:
Java is a programming language that can be used <br>to create web applications, Android apps, and much more.<br> it's easy to learn and it provides many features such as data types, operators, expressions, <br>statements, control structures and other elements that make up computer programs.
Using the java string replaceAll() method will return a new string with all of the sequence of characters matching regex and replacement string replaced.