In Dart to remove only the whitespace around a string, you can use the trim
method. The trim
method removes any leading and trailing whitespaces from the string. Here is an example:
<code>String myString = " This string has leading and trailing whitespaces. "; myString = myString.trim(); print(myString); // Output: "This string has leading and trailing whitespaces."</code>
I had a situation to remove whitespace and new line array the string inside the array/list, so we have to use a regular expression and the replaceAll
method to remove only the leading and trailing whitespaces in dart.
In Flutter, you can use the map
method to apply a function to each element of an array and return a new array with the modified elements. To strip whitespace and newline characters from each element of an array of strings, you can use the trim
method and the replaceAll
method. Here is an example of how you can use these methods to strip whitespace and newline characters from an array of strings:
<code>List<String> myArray = [" string with whitespaces\n", "another string\n"]; myArray = myArray.map((string) => string.trim().replaceAll("\n", "")).toList(); print(myArray); // Output: [string with whitespaces, another string]</code>
The trim
method removes any leading and trailing whitespaces from the string while the replaceAll
method replaces all occurrences of \n
from the string. Finally, the method toList
is used to convert the result of map to a List, as map return an Iterable.
You can also use the replaceAllMapped
method to remove all whitespaces and newline character with a single line of code.
<code>List<String> myArray = [" string with whitespaces\n", "another string\n"]; myArray = myArray.map((string) => string.replaceAllMapped(RegExp(r'^\s+|\s+$'), (match) => "")).toList();</code>
This will remove any whitespace characters (spaces and tabs) at the start and end of the string. Inside the string, the whitespaces will remain unchanged.
Hope this will help someone