The trim
method can be used to remove all the leading and trailing whitespace present in the string.
String trim()
This method returns a new string without any leading and trailing whitespace present in the calling string.
Note: A list of the characters that will be trimmed by the
trim
method can be found here.
The code below demonstrates how we can use the trim
method in Dart.
void main() {//create a string with whitespacesvar str = " \n\n\t this \t is a test \t\n ";print('str with whitespace :$str');var trimmedString = str.trim();print('TrimmedString : $trimmedString');}
In the code given above:
In line 3, we create a new string, str
, with some whitespaces at the start and end of the string. The whitespace includes a new-line character (\n) and a tab character (\t).
In line 5, we use the trim
method to remove the whitespace at the start and end of the string. This method returns a new string, which will be stored in trimmedString
.
In line 6, we print trimmedString
. trimmedString
will not have any whitespace at the start or end of the string.
Note: Only the whitespace at the beginning and end of the string is removed. The whitespace between the string is not removed.