stripmargin

Dart: How to remove leading spaces in a multiline string (using splitMapJoin)

As far as I know, there’s no built-in way to remove spaces from a multiline string in Dart, but you can write your own function to do this. For example, I just dug into the splitMapJoin method of the Dart String class, and wrote a stripMargin function like this:

String stripMargin(String s) {
    return s.splitMapJoin(
        RegExp(r'^', multiLine: true),
        onMatch: (_) => '\n',
        onNonMatch: (n) => n.trim(),
    );
}

How to left-justify a multiline Scala string

If you ever need to left-justify a multiline Scala string, the solution is to use the stripMargin method, as shown in this example:

def getWordFormatted(s: String): String = {
    s"""
      |
      |Word of the Day
      |---------------
      |Word: $s
    """.stripMargin
}

The | character has a special meaning when used in conjunction with stripMargin, so that method results in a string like this being output: