This has been asked several times for several languages but I can't get it to work. I have a string like this
String str = "This is a string.\nThis is a long string.";
And I'm trying to replace the \n
with <br />
using
str = str.replaceAll("(\r\n|\n)", "<br />");
but the \n
is not getting replaced. I tried to use this RegEx Tool to verify and I see the same result. The input string does not have a match for "(\r\n|\n)"
. What am i doing wrong ?
In order to replace all line breaks from strings replace() function can be used. String replace(): This method returns a new String object that contains the same sequence of characters as the original string, but with a given character replaced by another given character.
L. replaceAll("[\\\t|\\\n|\\\r]","\\\s");
Replace new line (\n) with HTML br tag in string using Javauses 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).
It works for me.
public class Program { public static void main(String[] args) { String str = "This is a string.\nThis is a long string."; str = str.replaceAll("(\r\n|\n)", "<br />"); System.out.println(str); } }
Result:
This is a string.<br />This is a long string.
Your problem is somewhere else.
A little more robust version of what you're attempting:
str = str.replaceAll("(\r\n|\n\r|\r|\n)", "<br />");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With