String.Replace not replacing vbCrlf
I am trying to replace all the occurrences of "\n" in the Text property of an ASP.NET TextBox with <br /> using String.Repalce function, but it doesn't seem to work:
taEmailText.Text.Replace("\n", "<br />")
As a solution I am using Regex.Replace:
New Regex("\n").Replace(taEmailText.Text, "<br />")
My question is why String.开发者_如何学运维Replace can't find "\n" for me, even though this solution has been proposed on many sites and it has worked for many people.
Thanks,
In .NET string objects are immutable, so String.Replace
returns a new string with the replacement. You need to assign the result:
taEmailText.Text = taEmailText.Text.Replace("\n", "<br />")
Also, rather than creating a new Regex
object—when you do need a regular expression—then there are static methods available:
result = Regex.Replace(input, pattern, replacement)
Edit (based on comment):
Just tested this:
Sub Main()
Dim result As String = "One\nTwo".Replace("\n", "<br />")
Console.WriteLine(result)
End Sub
and the result is:
One<br />Two
The problem is the result of the method call is immediated forgotten. You should read MSDN documentation a bit more carefully:
Returns a new string in which all occurrences…
Hence do:
taEmailText.Text = taEmailText.Text.Replace("\n", "<br />")
- Replace does not change the content of the input string. It returns newly created string.
You might want to replace both \r and \n or use
Environment.NewLine
constant.var replacedText = TextBox1.Text.Replace(Environment.NewLine, "<br />");
精彩评论