Search code examples
stringflutterdartwhitespace

How to remove all whitespace of a string in Dart?


Using trim() to eliminate white space in Dart and it doesn't work. What am I doing wrong or is there an alternative?

       String product = "COCA COLA";

       print('Product id is: ${product.trim()}');

Console prints: Product id is: COCA COLA


Solution

  • Try this

    String product = "COCA COLA";
    debugPrint('Product id is: ${product.replaceAll(new RegExp(r"\s+\b|\b\s"), "")}');
    

    Update:

    String name = '4 ever 1 k g @@ @';
    debugPrint(name.replaceAll(RegExp(r"\s+"), ""));
    

    Another easy solution:

    String name = '4 ever 1 k g @@ @';
    debugPrint(name.replaceAll(' ', ''));