I'm trying to replace all carrage returns with a <br/>
tag in C#. I thought this would take care of everything:
StringBuilder sb = new StringBuilder(s);
sb.Replace(System.Environment.NewLine, @"<br/>");
But apparently not. It doesn't seem to catch CR+LF
.
That will work if Environment.NewLine
is CR+LF, which it's likely to be on Windows. Of course it won't catch the situation where the string actually only contains line feeds, or only contains carriage returns. Perhaps you want:
StringBuilder sb = new StringBuilder(s).Replace("\r\n", "<br/>")
.Replace("\n", "<br/>")
.Replace("\r", "<br/>");
(Note that there's no point in using a verbatim string literal for "<br/>"
as there's no backslash in the string, and it's a single line.)
If you know for sure you will replace \r\n why not just use string.replace?
s.replace("\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