trimMargin

fun String.trimMargin(marginPrefix: String = "|"): String(source)

Trims leading whitespace characters followed by marginPrefix from every line of a source string and removes the first and the last lines if they are blank (notice difference blank vs empty).

Doesn't affect a line if it doesn't contain marginPrefix except the first and the last blank lines.

The lines in the original string can be separated with \r\n (CRLF), \n (LF), or \r (CR) characters, however, the lines in the resulting string will be separated solely with \n (LF) character.

Since Kotlin

1.0

Parameters

marginPrefix

non-blank string, which is used as a margin delimiter. Default is | (pipe character).

See also

Samples

import java.util.Locale
import kotlin.test.*

fun main() { 
   //sampleStart 
   val withoutMargin1 = """ABC
123
456""".trimMargin()
println(withoutMargin1) // ABC\n123\n456

val withoutMargin2 = """
    #XYZ
    #foo
    #bar
""".trimMargin("#")
println(withoutMargin2) // XYZ\nfoo\nbar 
   //sampleEnd
}