Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing all consecutive "\r\n or \n"s with one single <br>

Currently I am showing messages that I get from DB using only these two replacements:

text = text.replace("\r\n", "<br />");
text = text.replace("\n", "<br />");

but the problem is if there are many consecutive "\n"s I will have lots of
s or white spaces, I just want to make them all one. So what is your suggestion? Is there a quick replace method to make all consecutive \n\n\n\n\n\n\n only one just one br?

like image 466
Jimmy Page Avatar asked Nov 18 '25 06:11

Jimmy Page


1 Answers

You can use quantifier + to denote 1 or more.. Also, * means 0 or more..

text = text.replaceAll("\n+", "<br />");

text = text.replaceAll("[\n\r]+", "<br />");
like image 79
Rohit Jain Avatar answered Nov 20 '25 21:11

Rohit Jain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!