As stated in the title. for example:
Note: please check carefully the value of these three variables
String textA = 'this text contains many new line\n\n\n\nbut this ok, because there is a character after the new line';
String textB = 'I want remove all new Line because no character after new Line\n\n\n\n';
String textC = '\n\n\n\nAnd this still Ok, I dont want to remove all the new lines in front';
from that variable we can try print for see the result
textA will be
this text contains many new line
// new Line
// new Line
// new Line
but this ok, because there is a character after the new line
textB will be
I want remove all new Line because no character after new Line
// new Line - I want delete this new Line
// new Line - I want delete this new Line
// new Line - I want delete this new Line
textC will be
// new Line
// new Line
// new Line
And this still Ok, I dont want to remove all the new lines in front
you know we cant input \n (space form Enter your keyboard) to text field, when \n position in the last String, \n should be removed . How to solve this problem in dart or flutter?
CodePudding user response:
You can try this regex r'[\s\S]*\S'
.
void main() {
final regex = RegExp(r'[\s\S]*\S');
String textA =
'this text contains many new line\n\n\n\nbut this ok, because there is a character after the new line';
String textB =
'I want remove all new Line because no character after new Line\n\n\n\n';
String textC =
'\n\n\n\n\nAnd this still Ok, I dont want to remove all the new lines in front';
print('-');
print(regex.firstMatch(textA)?.group(0));
print('-');
print(regex.firstMatch(textB)?.group(0));
print('-');
print(regex.firstMatch(textC)?.group(0));
print('-');
}
Update: you can try str.trimRight()
too, i thing it is simple and working same.
final trimmed = '\nDart\n\n is fun\n\n'.trimRight();
print('-');
print(trimmed);
print('-');
// result
-
Dart
is fun
-
CodePudding user response:
I'm not sure in what kind of code you're trying to do this but the approach would be like this:
if string contains '\n' check if string ends with '\n' if not then you replace \n with ''.
CodePudding user response:
String does have one function trim() it will trim the space before and after the text.
Text(
'I want remove all new Line because no character after new Line\n\n\n\n'.trim(),
)
CodePudding user response:
You can replace \n to '' using this
var string = string.replaceAll('\n', '');