I have string as shown below. In dart trim() its removes the whitespace end of the string. My question is: How to replace spaces middle of string in Dart?
Example-1:
- Original: String _myText = "Netflix.com. Amsterdam";
- Expected Text: "Netflix.com. Amsterdam"
Example-2:
- Original: String _myText = "The dog has a long tail. ";
- Expected Text: "The dog has a long tail."
trim() removes the spaces from beginning and end of string.
Use the String. replace() method to replace all spaces in a string, e.g. str. replace(/ /g, '+'); . The replace() method will return a new string with all spaces replaced by the provided replacement.
replace() We can use replace() to remove all the whitespaces from the string.
To trim leading and trailing spaces or white space characters of a given string in Dart, you can use trim() method of String class.
Using RegExp like
String result = _myText.replaceAll(RegExp(' +'), ' ');
In my case I had tabs, spaces and carriage returns mixed in (i thought it was just spaces to start)
You can use:
String result = _myText.replaceAll(RegExp('\\s+'), ' ');
If you want to replace all extra whitespace with just a single space.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With