Removing carriage return and new-line from the end

2019-01-16 15:28发布

How do I remove the carriage return character (\r) and the new line character(\n) from the end of a string?

11条回答
疯言疯语
2楼-- · 2019-01-16 15:48
varName.replace(/[\r\n]/mg, '')                                              
查看更多
Lonely孤独者°
3楼-- · 2019-01-16 15:53

If you are using multiple platforms you are safer using this method.

value.TrimEnd(System.Environment.NewLine.ToCharArray());

It will account for different newline and carriage-return characters.

查看更多
Summer. ? 凉城
4楼-- · 2019-01-16 15:53

I use lots of erasing level

String donen = "lots of stupid whitespaces and new lines and others..."

//Remove multilines
donen = Regex.Replace(donen, @"^\s+$[\r\n]*", "", RegexOptions.Multiline);
//remove multi whitespaces
RegexOptions options = RegexOptions.None;
Regex regex = new Regex("[ ]{2,}", options);
donen = regex.Replace(donen, " ");
//remove tabs
char tab = '\u0009';
donen = donen.Replace(tab.ToString(), "");
//remove endoffile newlines
donen = donen.TrimEnd('\r', '\n');
//to be sure erase new lines again from another perspective
donen.Replace(Environment.NewLine, "");

and now we have a clean one row

查看更多
小情绪 Triste *
5楼-- · 2019-01-16 15:56

This was too easy -- for me I'm filtering out certain email items. I'm writing my own custom email junk filter. With \r and/or \n in the string it was wiping out all items instead of filtering.

So, I just did filter = filter.Remove('\n') and filter = filter.Remove('\r'). I'm making my filter such that an end user can use Notepad to directly edit the file so there's no telling where these characters might embed themselves -- could be other than at the start or end of the string. So removing them all does it.

The other entries all work but Remove might be the easiest?

I learned quite a bit more about Regex from this post -- pretty cool work with its use here.

查看更多
霸刀☆藐视天下
6楼-- · 2019-01-16 15:59

For us VBers:

TrimEnd(New Char() {ControlChars.Cr, ControlChars.Lf})
查看更多
Explosion°爆炸
7楼-- · 2019-01-16 16:01
String temp = s.replace("\r\n","").trim();

s being the original string.

查看更多
登录 后发表回答