Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove newlines from beginning and end of a string?

People also ask

How do I remove a newline from the end of a string?

Use the trim() method to remove the line breaks from the start and end of a string, e.g. str. trim() . The trim method removes any leading or trailing whitespace from a string, including spaces, tabs and all line breaks.

Does string trim remove newlines C#?

To trim a string like that we use C#'s Trim() method. One version of this method accepts characters to cut from both sides of the string. When we specify the carriage return character ( \r ) and line feed character ( \n ) there, the method removes all leading and trailing newlines.

Does string trim remove carriage return?

You can use trim() method if the string contains usual white space characters – space, tabs, newline, a carriage return. The recommended method is strip() to remove all the leading and trailing white space characters from the string.


Use String.trim() method to get rid of whitespaces (spaces, new lines etc.) from the beginning and end of the string.

String trimmedString = myString.trim();

String.replaceAll("[\n\r]", "");

This Java code does exactly what is asked in the title of the question, that is "remove newlines from beginning and end of a string-java":

String.replaceAll("^[\n\r]", "").replaceAll("[\n\r]$", "")

Remove newlines only from the end of the line:

String.replaceAll("[\n\r]$", "")

Remove newlines only from the beginning of the line:

String.replaceAll("^[\n\r]", "")

tl;dr

String cleanString = dirtyString.strip() ; // Call new `String::string` method.

String::strip…

The old String::trim method has a strange definition of whitespace.

As discussed here, Java 11 adds new strip… methods to the String class. These use a more Unicode-savvy definition of whitespace. See the rules of this definition in the class JavaDoc for Character::isWhitespace.

Example code.

String input = " some Thing ";
System.out.println("before->>"+input+"<<-");
input = input.strip();
System.out.println("after->>"+input+"<<-");

Or you can strip just the leading or just the trailing whitespace.

You do not mention exactly what code point(s) make up your newlines. I imagine your newline is likely included in this list of code points targeted by strip:

  • It is a Unicode space character (SPACE_SEPARATOR, LINE_SEPARATOR, or PARAGRAPH_SEPARATOR) but is not also a non-breaking space ('\u00A0', '\u2007', '\u202F').
  • It is '\t', U+0009 HORIZONTAL TABULATION.
  • It is '\n', U+000A LINE FEED.
  • It is '\u000B', U+000B VERTICAL TABULATION.
  • It is '\f', U+000C FORM FEED.
  • It is '\r', U+000D CARRIAGE RETURN.
  • It is '\u001C', U+001C FILE SEPARATOR.
  • It is '\u001D', U+001D GROUP SEPARATOR.
  • It is '\u001E', U+001E RECORD SEPARATOR.
  • It is '\u001F', U+0