1

I need to format text coming from user to HTML, but the input is multiple line and I have to replace all "enters" from that string to HTML <br /> tags.

String message = messageEditText.getText().toString();

This is the message I want to format. How can I format the string accordingly?

İsmet Alkan
  • 5,361
  • 3
  • 41
  • 64
Stepan Sanda
  • 2,322
  • 7
  • 31
  • 55

3 Answers3

5

try

message = message.replace ("\\r\\n", "<br>").replace ("\\n", "<br>");
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
  • `myString.replace(System.lineSeparator(), "
    ");` could potentially work, but this relies on the separator of the system the application is running on and the user input could be different than that.
    – Davio Oct 03 '14 at 07:13
  • 1
    Updated my answer. If this is not working, please provide more information. – Scary Wombat Oct 03 '14 at 07:16
  • Strings are immutable in Java. I love to write this. No, I'm not a nerd yet. This is the new trend. :D – İsmet Alkan Oct 03 '14 at 07:30
1

According to your operating system, the string will have newline character/s at the end of each line. Those can be \n or \r\n. Just write:

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

By this, if the current operating system uses \r\n those will be replaced within the first replacement, else if it's \n, they won't be found in first replacement, but will be replaced within the second one.

If you want to write some cool code, you can use the following:

System.getProperty("line.separator")

to get the new-line character/s of the system.

İsmet Alkan
  • 5,361
  • 3
  • 41
  • 64
1

You can use the double replacement as already suggested in other responses, but I would tend to prefer regex replacement, for concision of code:

yourString.replaceAll("\r?\n", "<br/>");

Or, of course Pattern equivalent, if you need to do the operation multiple times:

Pattern endOfLine = Pattern.compile("\r?\n");
endOfLine.matcher(yourString).replaceAll("<br/>");

Also, be careful with using System's line separator if user's input has been acquired from a web interface, or a remote system (depending on your use case, of course). User may use a different OS...

However, in all cases, make sure you do any EOL -> <br/> replacement, AFTER you have HTML-encoded any special characters in the user's input. Otherwise, the <br> tag will get encoded...

Ceredig
  • 131
  • 5