Dart: Use regexp to remove whitespaces from string
I couldn't believe that it was so complex to simply remove whitespaces from a string. So I came up with this solution, which I like much more than playing with regex:
myString.split(" ").join("");
print("test test1 test2".replaceAll(new RegExp(r"\s+\b|\b\s"), ""));
(without /ig
) worked for me.
These options are not supported in Dart this way.
/g
is equivalent toAll
inreplaceAll
/i
is equivalent tonew RegExp(r"...", caseSensitive: false)
I think this covers more bases:
textWithWhitespace.replaceAll(new RegExp(r"\s+\b|\b\s|\s|\b"), "")
The current accepted answer was not working for me. In the case where it was all whitespace, my whitespace was not removed
String whitespace = " ";
print(whitespace.replaceAll(new RegExp(r"\s\b|\b\s"), "").length);
//length is 4 here
This works fine even without using RegExp:
myString.replaceAll(" ", "");