Remove carriage return from string

I would like to insert the following into a string

<p>some text here</p>
<p>some text here</p>
<p>some text here</p>

I want it to go into a string as follows

<p>some text here</p><p>some text here</p><p>some text here</p>

i.e. without the carriage returns.

How do I achieve this?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Since you’re using VB.NET, you’ll need the following code:

Dim newString As String = origString.Replace(vbCr, "").Replace(vbLf, "")

You could use escape characters (r and n) in C#, but these won’t work in VB.NET. You have to use the equivalent constants (vbCr and vbLf) instead.

Method 2

How about:

string s = orig.Replace("n","").Replace("r","");

which should handle the common line-endings.

Alternatively, if you have that string hard-coded or are assembling it at runtime – just don’t add the newlines in the first place.

Method 3

If you want to remove spaces at the beginning/end of a line too(common when shortening html) you can try:

string.Join("",input.Split('n','r').Select(s=>s.Trim()))

Else use the simple Replace Marc suggested.

Method 4

In VB.NET there’s a vbCrLf constant for linebreaks:

Dim s As String = "your string".Replace(vbCrLf, "")

Method 5

Assign your string to a variable and then replace the line break and carriage return characters with nothing, like this:

 myString = myString.Replace(vbCrLf, "")

Method 6

You can also try:

string res = string.Join("", sample.Split(Environment.NewLine.ToCharArray())

Environment.NewLine should make it independent of platform.

Recommended Read:

Environment.NewLine Property

Method 7

How about using a Regex?

var result = Regex.Replace(input, "rn", String.Empty)

If you just want to remove the new line at the very end use this

var result = Regex.Replace(input, "rn$", String.Empty)

Method 8

For VB.net

vbcrlf = environment.newline…

Dim MyString As String = “This is a Test” & Environment.NewLine & ” This is the second line!”

Dim MyNewString As String = MyString.Replace(Environment.NewLine,String.Empty)

Method 9

I just had the same issue in my code today and tried which worked like a charm.

.Replace("rn")


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x